python – 需要帮助更快地进行排列

这是我的工作代码,我试图找到方法使其更快地找到有效的单词,我正在考虑为每个单词制作单独的字典列表,你会怎么想?

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中生成n长度位列表


下一篇:java – 字母表的每个排列最多29个字符?