2009-10-28 8 views
0

저는 현재 파이썬에 대해 깊이 파고 드는 중이고, 나는 (hackthissite.org)에서 내가 깰려고 노력하고있는 것을 발견했습니다. 제공된 단어 목록에있는 10 개의 단어를 해독해야합니다.파이썬 단어 해석기 암호 해독

def permutation(s): 
    if s == "": 
     return [s] 
    else: 
     ans = [] 
     for an in permutation(s[1:]): 
      for pos in range(len(an)+1): 
       ans.append(an[:pos]+s[0]+an[pos:]) 
     return ans 

def dictionary(wordlist): 
    dict = {} 
    infile = open(wordlist, "r") 
    for line in infile: 
     word = line.split("\n")[0] 
     # all words in lower case!!! 
     word = word.lower() 
     dict[word] = 1 
    infile.close() 
    return dict 

def main(): 
    diction = dictionary("wordlist.txt") 
    # enter all the words that fit on a line or limit the number 
    anagram = raw_input("Please enter space separated words you need to unscramble: ") 
    wordLst = anagram.split(None) 

    for word in wordLst: 
     anaLst = permutation(word) 
     for ana in anaLst: 
      if diction.has_key(ana): 
       diction[ana] = word 
       #print "The solution to the jumble is" , ana 
    solutionLst = [] 
    for k, v in diction.iteritems(): 
     if v != 1: 
      solutionLst.append(k) 
      print "%s unscrambled = %s" % (v, k) 
    print solutionLst 

main() 

함수 순열은 실제로 해독을 수행하는 코드 블록 인 것처럼 보입니다. 이 문제를 프로그래밍 방식으로 해결하는 방법을 이해하도록 도와 줄 수 있습니까?

Load the word list (dictionary) 
Input the words to unscramble 
For each word: 
    Find every permutation of letters in that word (permutation) 
    For each permutation: 
    Add this permutation to the solution list if it exists in the dictionary 
Print the solutions that were found. 

사전() 함수는 파일에서 단어 목록을 채우는된다

+0

들여 쓰기가 깨졌습니다. – SilentGhost

+0

그래, 파이썬을 올바르게 붙여 넣기 란 다소 힘든 일이었다. – adam

+0

만약 당신이'permutation' 함수를 실제 작업을하는 것으로 식별했다면, 그것을 혼자서 실행할 수 없으며 리턴하는 것을 볼 수 없습니까? – SilentGhost

답변

3

그의 의사는 같이 보입니다.

permutation() 함수는 주어진 단어의 모든 순열을 반환합니다.


순열() 함수

은 다음을 수행한다 :

for an in permutation(s[1:]): 

S [1] 절단 첫 문자 스트링을 반환한다. 정면에서자를 문자가 남아 있지 않을 때까지 재귀를 사용하여 순열()을 다시 호출한다는 것을 알 수 있습니다. 이 행을 이해하려면 재귀를 알아야합니다. 재귀를 사용하면이 알고리즘이 모든 문자 수를 처리 할 수 ​​있으며 여전히 우아합니다.

for pos in range(len(an)+1): 

각 문자 위치가 남아 있습니다.

첫 번째 문자 (이전에 잘 렸음)를 다른 모든 문자 사이의 각 위치로 이동하여 순열을 생성하십시오.


예를 들어 '시계'라는 단어를 사용하십시오. 나는 그 단어를 생성 한 모든 첫 글자를 가지고 위치를 이동했다

atchw

awtch atwch atcwh : 재귀 후, 다음 단어를 생성하는 루프가있을 것입니다. 계속해서 글자를 자르면 모든 순열이 만들어집니다.

+0

감사합니다 ... 프로그램은 지금 나를 위해 조금 더 명확합니다. – adam

+0

permutation() 함수에 대해 자세히 설명하는 업데이트를 추가했습니다. 나는 그것을 더 분명히하기를 희망합니다 : D – Kai

+0

대단히 감사합니다, 당신은 내 이해를 크게 도왔습니다. 다시 한 번 감사드립니다. – adam

0

훨씬 더 나은 솔루션이있다 (와우,이 아직 나의 가장 긴 대답해야합니다). 이 코드는 긴 단어가 많으면 비효율적입니다. 더 나은 아이디어는 사전에있는 모든 단어를 사전 적으로 분류하여 '신'이 'dgo'가되고 스크램블 된 단어에 대해 동일하게 수행하는 것입니다. O (n!) 대신 각 단어에 대해 O (nlogn)입니다.

0

이 코드도이 사이트에 작성했습니다. 아래 작업 코드 :

def import_dictionary(): 
    dictionary = [] 
    try: 
     file = open("C:\\Users\\Mason\\Desktop\\diction.txt", "r")#location of your dictionary or provided wordlist 
     fileContents = file.readlines() #read text file and store each new line as a string 
    finally: 
     file.close() 
    for i in range(len(fileContents)): 
     dictionary.extend(fileContents[i].split()) #changes the list by removing \n's from line breaks in text file 
    return dictionary 

def import_scrambled_words(): 
    scrambledWords = [] 
    try: 
     file = open("C:\\Users\\Mason\\Desktop\\scrambled.txt", "r") #location of your scrambled word file 
     fileContents = file.readlines() #read text file and store each new line as a string 
    finally: 
     file.close() 
    for i in range(len(fileContents)): 
     scrambledWords.extend(fileContents[i].split()) #changes the list by removing \n's from line breaks in text file 
    return scrambledWords 

def unscramble_word(scrambledWord): 
    countToMatch = len(scrambledWord) 
    matchedWords = [] 
    string = "" 

    for word in dictionary: 
     count = 0 
     for x in scrambledWord: 
      if x in word: 
       count += 1 
      if count == countToMatch: 
       matchedWords.append(word) 
       break 
    for matchedWord in matchedWords: 
     if len(matchedWord) == len(scrambledWord): 
      print(matchedWord) 
      string = matchedWord 
      break #this returns only one unscrambles word 
    return string 

if __name__ == '__main__': 
    finalString = "" 
    try: 
     scrambled = import_scrambled_words() 
     print(scrambled) 
     dictionary = import_dictionary() 
     for x in scrambled: 
      finalString += unscramble_word(x) 
      finalString +=", " 
     len(finalString) 

     print(finalString) 

    except Exception as e: 
     print(e) 

이 코드는 스크램블 단어의 저장된 파일에서 읽고 단어 목록에 대해 그것을 확인합니다 (난 그냥 추가로 내 경우에는 사전을 사용). alloned 30 초 안에 도전을 이기기 위해 나는 hackThissite에서 붙여 넣고 복사하여 내 스크램블 된 단어 파일에 붙여 넣었다. 저장되었습니다. 프로그램을 실행하고 복사하여 파이썬 콘솔의 출력을 붙여 넣었다.