Karol Bilicki - 1 year ago 94

Python Question

How to generate all 3-uppercase combinations in string?

For example:

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**