Sample python program to print all possible combinations of a given string. itertools is a powerful modules of python. it has a function named as combinations which prints r length of combinations of a given iterable. Let us see below example python code.

python program to print all possible combinations

#!/usr/bin/python
from itertools import combinations

#print all possible combinatiosn of "abc"
s = "abc"
for string in combinations(s,2):
	print ''.join(string)

The above program will print all possible combinations of given string “abc”.

bosch@bosch-Inspiron-N5050:~$ python comb.py 
ab
ac
bc
  • The python itertools function ‘combinations’ will generate all unique combinations if the iterable (which is a string in our example program) contains unique characters.
  • If the strings contains duplicate character it will generate duplicate combinations. For example if string is “aab”, combinations function will generate aa,ab,ab.
  • We can use set to print all unique combinations. See below example python program.
#!/usr/bin/python
from itertools import combinations

#print all possible combinatiosn of "abc"
s = "aac"
#create an empty set
comb = set()

for string in combinations(s,2):
	comb.add(''.join(string))

#print set
for item in comb:
	print item

combinations_with_replacement

combinations_with_replacement is another variant of combinations function which generate all possible combinations of a given iterable. It will generate r-length tuples, in sorted order, with repeated elements. For example if the given string is “abc” the it will generate aa,ab,ac,bb,bc,cc.

#!/usr/bin/python
from itertools import combinations_with_replacement 

#print all possible combinatiosn of "abc"
s = "abc"
for string in combinations_with_replacement(s,2):
	print''.join(string)

Output:

bosch@bosch-Inspiron-N5050:~$ python comb.py 
aa
ab
ac
bb
bc
cc

 

Ref:

https://docs.python.org/2/library/itertools.html



Related Contents to follow