【发布时间】:2019-06-21 08:36:48
【问题描述】:
我想要使用术语的所有字符组合单词。示例:
word = 'aan'
result = ['ana', 'naa', 'aan']
条款:
字符 'a' 的数量 -> 2
字符数'n' -> 1
【问题讨论】:
-
到目前为止你有什么尝试?
标签: python string combinations permutation discrete-mathematics
我想要使用术语的所有字符组合单词。示例:
word = 'aan'
result = ['ana', 'naa', 'aan']
条款:
字符 'a' 的数量 -> 2
字符数'n' -> 1
【问题讨论】:
标签: python string combinations permutation discrete-mathematics
我尝试了一种单行解决方案,并在列表中给出了结果
您可以使用itertools 包中的排列工具来获取所有排列(而非组合)解决方案
from itertools import permutations
word = 'aan'
list(set([ ''.join(list(i)) for i in permutations(word,len(word))]))
【讨论】:
如果我真的明白你想要什么,我会这样做:
from itertools import permutations
result = set()
for combination in permutations("aan"):
result.add(combination)
【讨论】:
您可以将递归与生成器一起使用:
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']
【讨论】: