简体   繁体   中英

How to make combinations in python?

How to generate all 3-uppercase combinations in string? For example:

f("abcde") => ['ABCde', 'aBCDe', 'abCDE', 'ABcDe', 'ABcdE' ...]

One way would be to generate the cartesian product of the letters (in both their lower-case and upper-case variety), then only keep them if there are exactly 3 uppercase letters

from itertools import product
def combs(s, n):
    pairs = tuple(i.lower() + i.upper() for i in s)
    for i in product(*pairs):
        if sum(1 for j in i if j.isupper()) == n:
            yield ''.join(i)

Example

for s in combs('abcde', 3):
    print(s)

Output

abCDE
aBcDE
aBCdE
aBCDe
AbcDE
AbCdE
AbCDe
ABcdE
ABcDe
ABCde
def f(s):
    r = []
    for i in range(1, len(s)-1):
        for j in range(i+1, len(s)):
            r.append(s[:i].capitalize() + s[i:j].capitalize() + s[j:].capitalize())
    return r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM