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

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

  • 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.

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.

Output:

 

Ref:

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




Related Contents to follow