在Python中细分itertools.permutations过程

时间:2014-07-02 12:28:06

标签: python memory-management itertools

有没有办法细分占用大量内存的进程(在这种情况下为itertools.permutations),以提高效率并且不会耗尽内存?

1 个答案:

答案 0 :(得分:0)

你已经用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 word