How can I create all possible combination of words from characters of given word in Python?

python

#1

Hi,

I want to create all possible combination of words from characters of input string in python and length of words must be similar to input word. Let’s say I have given input as “READ” then other combination of words would be ERAD, ERDA, REDA, ARED, ARDE, AEDR, AERD, DEAR …

Please help me to create this program.

Regards,
Imran


#2

@Imran,

You can use library itertools. This library is useful to find the permutations and combinations. Here function permutations allows to get permutation of N values within a list and order matters.

For instance, selecting N=2 values from [A,B,C] can be done as:

Code

s='ABC'
print list(itertools.permutations(s,2))

Output

[('A','B'),('B','A'),('B','C'),('C','B'),('A','C'),('C','A')]

if we will use combinations, order does not matter and output will be as:

Code

s='ABC'
print list(itertools.combinations(s,2))

Output

[('A','B'),('B','C'),('A','C')]

You can use this library to generate all possible combinations of words. Here value of N would be the leght of the string. Let’s look at the below code:

Code

  import itertools
    s='READ'
    t=list(itertools.permutations(s,len(s)))
    for i in range(0,len(t)):
        print ''.join(t[i])

Output

READ
REDA
RAED
RADE
RDEA
RDAE
ERAD
ERDA
EARD
EADR
EDRA
EDAR
ARED
ARDE
AERD
AEDR
ADRE
ADER
DREA
DRAE
DERA
DEAR
DARE
DAER

Regards,
Mark