Python Forum
how to get all the possible permutation and combination of a sentence in python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to get all the possible permutation and combination of a sentence in python (/thread-19099.html)



how to get all the possible permutation and combination of a sentence in python - sodmzs - Jun-13-2019

Hi,

I have a text say for example,

t = "life is amazing"

by doing,

from nltk.tokenize import word_tokenize
words = word_tokenize(t)

what I got,


>>>words = ["life","is","amazing"]


and I have multiple lists in a dictionary each having a list of synonyms.
for example,

{'life' : [life,living,aliveness,spirit,...], 'is' : [be, exist, follow,..],
'amazing' : [vex,pose,flummox,..], ... }

with the help of the following code,

for i in range(0,len(dict)):
    for j in range(0,len(words)):
        if words[j] == (list(dict)[i]):
            for k in range(0,len((dict)[words[j]])):
                z = t.replace(words[j],(dict)[words[j]][k])
                print(z)
how the output I am getting is,

life is amazing
living is amazing
aliveness is amazing
spirit is amazing
...
life be amazing
life exist amazing
life follow amazing
...
life is vex
life is pose
life is flummox
...

and how the output I want ?

I want all the permutation combinations of the synonyms in the sentence.
Assume that we have at least or exactly 5 identified synonyms for each of our words.
Then totally there are 3 words in the selected first line of 't'.
Therefore 5 to the power of 3 sentences = 125 sentences are possible to generate.
Any help regarding this, will be really appreciable.


RE: how to get all the possible permutation and combination of a sentence in python - perfringo - Jun-13-2019

(Jun-13-2019, 06:53 AM)sodmzs Wrote: I want all the permutation combinations

There is built-in itertools module in Python which have permutations and combinations