I am trying to create a program to generate all possible capitalization cases of a string in python. For example, given 'abcedfghij', I want a program to generate: Abcdefghij ABcdef.. . . aBcdef.. . ABCDEFGHIJ
And so on. I am trying to find a quick way to do it, but I don't know where to start.
All combination of string in java is the companion problem to find permutation of the string . The combination generated from the algorithm has range in length from one to the length of the string. Two combinations that differ only in ordering of their characters are the same combination.
A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are Permutation of each other.
To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.
Similar to Dan's solution, but much simpler:
>>> import itertools
>>> def cc(s):
... return (''.join(t) for t in itertools.product(*zip(s.lower(), s.upper())))
...
>>> print list(cc('dan'))
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
from itertools import product, izip
def Cc(s):
s = s.lower()
for p in product(*[(0,1)]*len(s)):
yield ''.join( c.upper() if t else c for t,c in izip(p,s))
print list(Cc("Dan"))
prints:
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With