Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python程序非常慢_Python_Performance_Itertools_Words - Fatal编程技术网

python程序非常慢

python程序非常慢,python,performance,itertools,words,Python,Performance,Itertools,Words,这个程序生成字母组合并检查它们是否是单词,但是程序非常慢,每秒只生成几个单词。请告诉我为什么它非常慢,以及我需要什么使它更快 import itertools for p1 in itertools.combinations('abcdefghijklmnopqrstuvwxyz', 4): with open('/Users/kyle/Documents/english words.txt') as word_file: english_words = set(wo

这个程序生成字母组合并检查它们是否是单词,但是程序非常慢,每秒只生成几个单词。请告诉我为什么它非常慢,以及我需要什么使它更快

import itertools 

for p1 in itertools.combinations('abcdefghijklmnopqrstuvwxyz', 4):
    with open('/Users/kyle/Documents/english words.txt') as word_file:
        english_words = set(word.strip().lower() for word in word_file)

    def is_english_word(word):
        return word.lower() in english_words

    print ''.join(p1),"is", is_english_word(''.join(p1))

这很慢,因为您正在为每个循环迭代重新读取一个文件,并创建一个新的函数对象。这两件事都不依赖于循环变量;将它们移出循环以仅运行一次

此外,简单函数可以内联;调用函数的成本相对较高。也不要调用
''.join()
两次。而且您只使用小写字母生成单词,因此
.lower()
是多余的:

with open('/Users/kyle/Documents/english words.txt') as word_file:
    english_words = set(word.strip().lower() for word in word_file)

for p1 in itertools.combinations('abcdefghijklmnopqrstuvwxyz', 4):
    word = ''.join(p1)
    print '{} is {}'.format(word, word in english_words)
由于您正在生成长度为4的单词,因此只需从英语单词文件中加载长度为4的单词即可节省一些内存:

with open('/Users/kyle/Documents/english words.txt') as word_file:
    english_words = set(word.strip().lower() for word in word_file if len(word.strip()) == 4)

你的词表有多大?每个组合你都要读一次。单词列表是所有英语单词的列表。谢谢你解决了这个问题,我会尽快接受你的答案。谢谢这让它工作得很好,我如何使它只显示
正确的
单词?或者这是一个错误的地方,我想我应该在“编程难题与代码高尔夫”“站点。是否使用
if
测试
if英语单词:打印单词而不是当前的
print
语句?这并不是很难做到。@kylek:但只打印我过滤的
英语单词集,而不是重新生成所有可能的4个字母组合,会更快。我在答案末尾生成的集合包含所有4个字母的单词,它们将与您的4个字母组合循环相匹配。谢谢您的帮助,所有问题都已解决,我没有其他问题了。