这是我的工作代码,我正在尝试寻找方法来使其更快地找到有效单词,我正在考虑可能为每个单词制作单独的字典列表,你们怎么看?
import random
import itertools
file_name='words.txt'
def load_words():
try:
f=open(file_name,'r')
str1=f.read()
f.close()
except:
print('Problem opening the file',file_name)
list1=[]
list1=str1.split()
return(list1)
def is_valid(str1,list1):
valid=False
if str1 in list1:
valid=True
return valid
def generate(words,letters):
answers=[]
for length in range(2,len(letters)+1):
for x in itertools.permutations(letters,length):
word=''
for let in x:
word+=let
if is_valid(word.upper(),words):
answers.append(word)
print(word)
print(answers)
def main():
words=load_words()
letters = input('Enter your letters')
answers = generate(words,letters)
main()
最佳答案
如果您太热衷于以降低可读性为代价来提高速度,您可以尝试以下方法
def is_valid(str1,list1):
return str1 in list1
words=["BAD","CAB","BEC"]
def generate2(words,letters):
answers=[]
[[answers.append(''.join(x).upper()) for x in itertools.permutations(letters,length) if ''.join(x).upper() in words] for length in range(2,len(letters)+1)]
#print(answers)
return answers
List comprehension is faster than loops 。所以将两个循环组合成一个单一的理解。除此之外,声明
word=''
for let in x:
word+=let
if is_valid(word.upper(),words):
可以组合到 if
is_valid(''.join(x).upper,words)
甚至 ''.join(x).upper in words
,记住函数调用是昂贵的。我做了一个速度比较,看起来列表理解的运行速度提高了 50%。
现在由你来决定
>>> stmt1="""
def is_valid(str1,list1):
valid=False
if str1 in list1:
valid=True
return valid
words=["BAD","CAB","BEC"]
def generate1(words,letters):
answers=[]
for length in range(2,len(letters)+1):
for x in itertools.permutations(letters,length):
word=''
for let in x:
word+=let
if is_valid(word.upper(),words):
answers.append(word)
#print(word)
#print(answers)
return answers
generate1(words,['A','B','C','D','E'])
"""
>>>
>>> stmt2="""
def is_valid(str1,list1):
return str1 in list1
words=["BAD","CAB","BEC"]
def generate2(words,letters):
answers=[]
[[answers.append(''.join(x).upper()) for x in itertools.permutations(letters,length) if ''.join(x).upper() in words] for length in range(2,len(letters)+1)]
#print(answers)
return answers
generate2(words,['A','B','C','D','E'])
"""
>>>
>>> t1=timeit.Timer(stmt=stmt1)
>>> t2=timeit.Timer(stmt=stmt2)
>>> t1.repeat(number=1000)
>>> t2=timeit.Timer(stmt=stmt2)
>>> t1.repeat(number=1000)
[0.47923321640178074, 0.4353549521401874, 0.4362746333173959]
>>> t2.repeat(number=1000)
[0.2536238984591819, 0.2470974750062851, 0.24726312027155473]
关于python - 需要帮助更快地进行排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8331750/