2 回答
TA贡献1816条经验 获得超6个赞
而不是根据长列表检查所有排列(59127 个字母很好,但4 037 91210 个字母的可能性无法计算)。我建议根据字母检查列表(复杂性现在取决于列表的长度,根据定义,列表的长度比所有排列都短)。这允许您不将整个字典加载到内存中,因为它可能非常大:
from collections import Counter
rack = Counter('QOFTHEA')
with open('words.txt') as f:
for word in (i[:-1] for i in f):
if len(word) > len(rack):
continue
word_counter = Counter(word)
for l, c in word_counter.items():
if l not in rack:
break
else:
if c > rack[l]:
break
else:
print(word)
如果由于某种原因您不想使用标准库:
def Counter(iterable):
dic = {}
for i in iterable:
if i not in dic:
dic[i] = 1
dic[i] += 1
return dic
TA贡献1847条经验 获得超11个赞
您可以使用itertools.permutations和itertools.chain.from_iterable:
from itertools import chain, permutations
rack = 'QOFTHEA'
lo, hi = 2, 7
for perm in chain.from_iterable(permutations(rack, i) for i in range(lo, hi + 1)):
print(perm)
如果你想要一个字符串而不是一个字符元组,你可以做''.join(perm).
添加回答
举报