Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 464
Gary Oldfaber Avatar asked Dec 13 '10 04:12

Gary Oldfaber


1 Answers

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
like image 183
Steve Tjoa Avatar answered Oct 18 '22 08:10

Steve Tjoa