【问题标题】:How can I generate a list of all possible permutations of several letters? [duplicate]如何生成几个字母的所有可能排列的列表? [复制]
【发布时间】:2014-01-29 18:19:35
【问题描述】:

所以我正在制作一个单词生成器,它接受几个输入的字母,将它们放在所有可能的位置,然后将它们与文档匹配以查找单词。如果我接近这个错误,请告诉我!如果不是,我该怎么做? 谢谢

【问题讨论】:

  • 注意,对于一个字符串len(s) == n,排列的数量是n!;这会很快变大(例如,我的用户名有 3,628,800 种排列)。

标签: python permutation alphabetical


【解决方案1】:

要生成给定字母列表的所有排列,请使用 itertools 模块。

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

【讨论】:

  • 如果列表中有 7 个字母,这也会产生 6 个字母单词的排列吗?还是5?还是4?等等。
  • 不,只有 7 个字母的排列,但 itertools 肯定可以满足您的需求,请参阅 docs.python.org/2/library/itertools.html
  • 谢谢你
  • @codeman99 你可以,只需传递你想要的长度作为第二个参数。 itertools.permutations( list_of_letters, length )docs
【解决方案2】:

您可以编写自己的函数(:

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

【讨论】:

    【解决方案3】:

    反向运行它可能会更快:索引您的文档,并为每个单词查看它是否是您的字母列表的子集。

    【讨论】:

      【解决方案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
      

      这是实现算法的另一种方法。

      【讨论】:

        猜你喜欢
        • 2012-12-03
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        相关资源
        最近更新 更多