使用术语获取字符的所有组合或排列
Getting All Combinations or Permutations of a Character using terms
我想要使用术语的字符的所有组合词。示例:
word = 'aan'
result = ['ana', 'naa', 'aan']
条款:
字符数 'a' -> 2
字符数 'n' -> 1
如果我真的明白你想要什么,我会这样做:
from itertools import permutations
result = set()
for combination in permutations("aan"):
result.add(combination)
我尝试了一个单行解决方案,并在列表中给出了结果
您可以使用 itertools 包中的排列工具来获取所有排列(而非组合)解决方案
from itertools import permutations
word = 'aan'
list(set([ ''.join(list(i)) for i in permutations(word,len(word))]))
您可以对生成器使用递归:
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']
我想要使用术语的字符的所有组合词。示例:
word = 'aan'
result = ['ana', 'naa', 'aan']
条款:
字符数 'a' -> 2
字符数 'n' -> 1
如果我真的明白你想要什么,我会这样做:
from itertools import permutations
result = set()
for combination in permutations("aan"):
result.add(combination)
我尝试了一个单行解决方案,并在列表中给出了结果
您可以使用 itertools 包中的排列工具来获取所有排列(而非组合)解决方案
from itertools import permutations
word = 'aan'
list(set([ ''.join(list(i)) for i in permutations(word,len(word))]))
您可以对生成器使用递归:
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']