How can I generate a list of all possible permutations of several letters?

So, I create a word generator that takes a few letters entered, puts them in all possible positions and compares them with the document to find the words. If I'm approaching this wrong, tell me! If not, how can I do this? Thanks

+3
source share
4 answers

to generate all permutations of a given list of letters, use the itertools module.

import itertools 
for word in itertools.permutations( list_of_letters ):
   print ''.join(word)
+8
source

It may be faster to run it in the reverse order: index your document and for each word, see if it is a subset of your list of letters.

+2
source

(:

def permutation(head, tail=''):
    if len(head) == 0: 
        print tail
    else:
        for i in range(len(head)):
            permutation(head[0:i] + head[i + 1:], tail + head[i])
+2
def allpermutationsOfString(words):
  if len(words) == 1:
    return [words]
  result = []
  for index, letter in enumerate(words):
    wordWithoutLetter = words[:index] + words[index+1:]
    result = result + [letter + word for word in allpermutationsOfString(wordWithoutLetter)]
  return result

print allpermutationsOfString("watup") #will print all permutations of watup

.

0

All Articles