4

So I am making a word generator that takes several inputted letters, puts them in all possible positions, and matches them with a document to find words. If I am approaching this wrong please tell me! If not how can I do this? Thanks

codeman99
  • 87
  • 2
  • 2
  • 6
  • 1
    Note that, for a string `len(s) == n`, the number of permutations is `n!`; this gets big pretty fast (there are 3,628,800 permutations of my user name, for example). – jonrsharpe Jan 29 '14 at 18:24

4 Answers4

9

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)
Colin Bernet
  • 1,354
  • 9
  • 12
  • If I have 7 letters in the list will this also generate permutaions of 6 letter words? Or 5? Or 4? ect. – codeman99 Jan 29 '14 at 18:26
  • no, only permutations of 7 letters, but itertools for sure does what you want, see http://docs.python.org/2/library/itertools.html – Colin Bernet Jan 29 '14 at 18:29
  • @codeman99 You can, just pass length that you want as second argument. `itertools.permutations( list_of_letters, length )`[docs](https://docs.python.org/2/library/itertools.html#itertools.permutations) – mmaksitaliev Apr 29 '18 at 16:21
3

You can write your own function (:

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])
Vlad Sonkin
  • 395
  • 3
  • 4
2

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

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
0
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

Here's another way to implement the algorithm.

Brian Yeh
  • 3,119
  • 3
  • 26
  • 40