python混合求解算法

python混合求解算法,python,Python,我需要为给定的问题编写一个代码 我有一个单词,我需要找到所有可能的单词组合,与文件中给定的单词列表相匹配 这是我的密码。我能做得更好吗。我相信这是可能的。请建议 dict = {} file = open("/usr/share/dict/words", "r") for word in file:

我需要为给定的问题编写一个代码

我有一个单词,我需要找到所有可能的单词组合,与文件中给定的单词列表相匹配

这是我的密码。我能做得更好吗。我相信这是可能的。请建议

dict = {}                                                
file = open("/usr/share/dict/words", "r")                

for word in file:                                        #Iterate through every word in the dictionary
        word = word.strip().lower()                        #Strip newlines and send to lowercase
        sorted_word = ''.join(sorted(word))                #Alphabetically sort the word
        if sorted_word in dict:                                #Check if sorted_word is already a key
                if word not in dict[sorted_word]:        #Make sure word is not already in the list under the key sorted_word
                        dict[sorted_word].append(word)        #Add to list under the key sorted_word
        else:                                                #If not in dictionary
                dict[sorted_word] = [word]                #Create new list with one entry
while(True):                                                #Loop until quit is typed
        jumble = raw_input("Enter a jumble to decode or 'quit': ")        #Get input
        jumble = jumble.lower()                                #Send jumble to lower
        if(jumble == "quit"):                                #Quit if quit is typed
                break
        jumble = ''.join(sorted(jumble))                #Sort jumble alphabetical
        if jumble in dict:                                #If sorted jumble exists in dictionary
                results = dict[jumble]                        #Get list of words that match jumble
                for result in results:                        #Loop through list printing results
                        print result,                        #Trailing , designates that there should be a space between entries
                print ""                                #Print newlines
        else:                                                #Jumble not found in dictionary print message
                print "Results for jumble not found"
您可以使用并简化以下步骤:

import collections

# If you try to look up a key that doesn't exist in `words`,
# it will create a new `set()` for that key and return it.
words = collections.defaultdict(set)
with open("/usr/share/dict/words", "r") as file:
    for word in file:
        word = word.strip().lower()
        sorted_word = "".join(sorted(word))
        # `words[sorted_word]` is a set, so there's no need to check if
        # `word` is already in it.
        words[sorted_word].add(word)

这个问题似乎离题了,因为您需要检查工作代码。这是你个人的看法。我不想复习。我想要一个比这更好的解决方案。如果它不起作用,我会要求进行复查。@user1162512这当然是一个代码复查类型的问题。具体来说,从“避免主要基于观点的问题,或可能引起讨论而不是答案的问题”中可以看出,寻求一般性建议以改进代码本身并不适合确定的答案。