Karol Bilicki - 9 months ago 54

Python Question

How to generate all 3-uppercase combinations in string?

For example:

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

Answer Source

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
```