Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination of all possible cases of a string

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.

like image 387
peacey Avatar asked Jul 19 '11 12:07

peacey


People also ask

What is combination of a string?

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.

What is a permutation of a string?

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.

How do you print all possible combinations of a string in Python?

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.


2 Answers

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']
like image 143
Ferdinand Beyer Avatar answered Oct 18 '22 21:10

Ferdinand Beyer


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']
like image 24
Dan D. Avatar answered Oct 18 '22 20:10

Dan D.