使用术语获取字符的所有组合或排列

时间:2019-06-21 08:36:48

标签: python string combinations permutation discrete-mathematics

我希望使用术语的所有组合单词。示例:

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

条款:

字符“ a”的数量-> 2
字符“ n”的数量-> 1

3 个答案:

答案 0 :(得分:1)

我尝试了一种线性解决方案,并将结果列在列表中

您可以使用itertools软件包中的置换工具来获得所有置换(而非组合)解决方案

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

答案 1 :(得分:0)

如果我真的了解你想要什么,我会那样做:

processContents="skip"

答案 2 :(得分:0)

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

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