繁体   English   中英

在Python中细分itertools.permutations流程

[英]Subdivide itertools.permutations process in Python

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

您已经使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM