【问题标题】:Getting All Combinations or Permutations of a Character using terms使用术语获取字符的所有组合或排列
【发布时间】:2019-06-21 08:36:48
【问题描述】:

我想要使用术语的所有字符组合单词。示例:

word = 'aan'
result = ['ana', 'naa', 'aan']

条款:

字符 'a' 的数量 -> 2
字符数'n' -> 1

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: python string combinations permutation discrete-mathematics


【解决方案1】:

我尝试了一种单行解决方案,并在列表中给出了结果

您可以使用itertools 包中的排列工具来获取所有排列(而非组合)解决方案

from itertools import permutations
word = 'aan'
list(set([ ''.join(list(i)) for i in permutations(word,len(word))]))

【讨论】:

  • 对 word = 'ain' 不起作用。结果 = ['ain', 'ani', 'nai']
  • 您首先提出的问题更多的是排列而不是组合,请尝试使用 itertools 包并使用适合您问题的方法。 docs.python.org/3/library/itertools.html
【解决方案2】:

如果我真的明白你想要什么,我会这样做:

from itertools import permutations

result = set()
for combination in permutations("aan"):
    result.add(combination)

【讨论】:

    【解决方案3】:

    您可以将递归与生成器一起使用:

    from collections import Counter
    def combo(d, c = []):
      if len(c) == len(d):
        yield ''.join(c)
      else:
        _c1, _c2 = Counter(d), Counter(c)
        for i in d:
          if _c2.get(i, 0) < _c1[i]:
            yield from combo(d, c+[i])
    
    word = 'aan'
    print(list(set(combo(word))))
    

    输出:

    ['aan', 'naa', 'ana']
    

    word = 'ain'
    print(list(set(combo(word))))
    

    输出:

    ['ina', 'nia', 'nai', 'ani', 'ian', 'ain']
    

    【讨论】:

      猜你喜欢
      • 2011-07-04
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2020-08-21
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多