简体   繁体   中英

Subdivide itertools.permutations process in Python

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

You've backed yourself into a corner with itertools.permutations . Do you really need to check all of the possible permutations? Your dictionary is pretty small, so just iterate over the dictionary itself and validate each word:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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