2013-12-10 2 views
0

주어진 문제에 대한 코드를 작성해야합니다.python jumble solver algorithm

나는 단어가 제공되며 파일의 주어진 단어 목록과 일치하는 가능한 모든 조합을 찾아야합니다.

여기 내 코드가 있습니다. 내가 더 잘 할 수 있을까? 나는 그것이 가능할 것이라고 확신한다. 제발 제안 해주세요.

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" 
+6

이 질문은 당신이 코드를 작업의 리뷰를 원하기 때문에 오프 주제 것으로 보인다. [코드 검토] (http://codereview.stackexchange.com/)에 적합합니다. – Tim

+0

이것은 개인적인 의견입니다. 나는 리뷰를 원하지 않는다. 나는 이것보다 나은 해결책을 원한다. 작동하지 않을 때를 대비하여 검토를 요청했을 것입니다. – PythonEnthusiast

+0

@ user1162512 이것은 확실히 코드 검토 유형 질문입니다. 특히, [about] (http://stackoverflow.com/about)에서 : "주로 의견을 기반으로하는 질문을 피하거나 답변보다는 토론을 생성 할 가능성이있는 질문을 피하십시오." 코드를 더 좋게 만드는 일반적인 제안을 요청하는 것이 확실한 답을 얻는 것은 아닙니다. – jonafato

답변

1

이 일부를 단순화하기 위해 setcollections.defaultdict을 사용할 수

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)