-2

How do you generate all combinations of lower and upper characters in a word? e.g:

'abc'['abc', 'ABC', 'Abc', 'ABc', 'aBC', 'aBc', 'abC', 'Abc']

'ab'['ab', 'AB', 'Ab', 'aB']

iacob
  • 20,084
  • 6
  • 92
  • 119
ycjcl868
  • 432
  • 3
  • 7
  • 18
  • I have a feeling you're "doing this backwards" and generating all possible capitalizations unnecessarily. That being said, you could generate all the possible capitalizations with with recursion (each letter is either upper case or lower case -- recurse on both) or or something like `itertools.product([(c.lower(), c.upper()) for c in word])`. – jedwards Jun 09 '18 at 14:11

2 Answers2

12

You can achieve this by zipping the upper and lower case letters and taking their cartesian product:

import itertools

chars = "abc"
results = list(map(''.join, itertools.product(*zip(chars.upper(), chars.lower()))))

print(results)
>>>['ABC', 'ABc', 'AbC', 'Abc', 'aBC', 'aBc', 'abC', 'abc']

To visualise how this works:

  1. zip is creating our 3 'axes' for us, each with 2 points (the upper / lower cases)
    [('A', 'a'), ('B', 'b'), ('C', 'c')].
  2. product takes the cartesian product of these axes, i.e. the 8 possible coordinates corresponding to the corners of the unit cube it creates:
enter image description here enter image description here
1. Create axes 2. Take Cartesian product
iacob
  • 20,084
  • 6
  • 92
  • 119
2

Using recursion:

def foo(word):
    if len(word) == 1:
        return [word.lower(), word.upper()]
    else:
        return [f"{j}{i}" for j in foo(word[0]) for i in foo(word[1:])]

s = "abc"
print(foo(s))
>>> ['abc', 'abC', 'aBc', 'aBC', 'Abc', 'AbC', 'ABc', 'ABC']
iacob
  • 20,084
  • 6
  • 92
  • 119
shahaf
  • 4,750
  • 2
  • 29
  • 32