gpt4 book ai didi

python程序很慢

转载 作者:太空狗 更新时间:2023-10-30 01:49:03 24 4
gpt4 key购买 nike

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

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)

关于python程序很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17125891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com