是否有任何方法细分占用大量内存的进程(在本例中为itertools.permutations),以提高效率和不耗尽内存?
发布于 2014-07-02 14:42:17
你已经用itertools.permutations把自己逼到了绝境。你真的需要检查所有可能的排列吗?您的字典非常小,所以只需遍历字典本身并验证每个单词:
import itertools
from collections import Counter
with open('/usr/share/dict/american-english', 'r') as handle:
dictionary = frozenset(line.strip() for line in handle)
def existing_words(letters, length):
letters_counter = Counter(letters)
letters_set = frozenset(letters)
for word in dictionary:
if len(word) != length:
continue
if set(word) <= letters_set and Counter(word) <= letters_counter:
yield word
if __name__ == '__main__':
for word in existing_words('abcdefghijklmnopqrst', 5):
print wordhttps://stackoverflow.com/questions/24531076
复制相似问题