Search code examples
pythonpermutationsubsetpython-itertools

Generating subsets of a permuted wordlist in Python


I have a list of words and I need to generate all possible permutations of these, with one caveat.

I currently use the following code:

from itertools import permutations

wordlist = ["word1", "word2", "word3"]

for perm in permutations(wordlist):
    print "".join(perm)

which gives the output:

word1word2word3
word1word3word2
...
word3word2word1

However I also need it to print subsets these words, such as:

word1    
word1word2
word2word1
...

But I haven't the slightest idea how to do this. Where do I begin? What should I read?


Solution

  • Edited:

    from itertools import permutations
    
    xlist = ["word1", "word2", "word3"]
    
    for n in range(1, len(xlist)+1):
        for perm in permutations(xlist, n):
            print "".join(perm)
    

    Edit: output:

    word1
    word2
    word3
    word1word2
    word1word3
    word2word1
    word2word3
    word3word1
    word3word2
    word1word2word3
    word1word3word2
    word2word1word3
    word2word3word1
    word3word1word2
    word3word2word1