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

瘦欲@ 提交于 2019-12-31 01:50:11

问题


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


回答1:


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)



回答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.




回答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])



回答4:


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.



来源:https://stackoverflow.com/questions/21439346/how-can-i-generate-a-list-of-all-possible-permutations-of-several-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!