如何提高功能效率?

时间:2019-03-26 10:27:58

标签: python performance time-complexity

所以我写了这个小python程序,它从输入的字母和语言创建字谜,但是一旦输入的单词有太多可能的输出或只是太长,它就会崩溃。如何改善我的代码,使其变得更高效/更有效率?

def createAnagrams(word, language):
    dictLanguage = enchant.Dict(language) #library that can check if word exists 
    existingWords = [] 

    for i in range(1, len(word)+1):
        for j in permutations(word, i):
            existingWords.append("".join(j))
    existingWords = set(existingWords) #remove duplicates
    existingWords = list(existingWords) #change back to list to be able to iterate through it
    for k in range(len(existingWords)):
        if(dictLanguage.check(existingWords[k])) and (len(existingWords[k])>1): #if word exists and longer than 1 char print it
            print(existingWords[k])

适用于诸如“你好”,“帕特里克”,“昨天”之类的单词,但会因诸如“公告”,“订阅”之类的单词而崩溃。希望有更长的单词的预期输出。

预先感谢

1 个答案:

答案 0 :(得分:0)

我怀疑您的程序崩溃的原因是某种内存不足错误。具体来说,您将创建一个包含“公告”的所有子字符串的所有排列的列表(6749977113个)。这不是一个好主意...

我建议为language实现一个trie并根据给定单词中的字母进行树搜索,以获得word中包含的所有语言单词,以获得列表子字符串。当然,将它们组合成完整的字谜是另一个问题。

相关问题