【发布时间】:2011-07-11 06:35:51
【问题描述】:
嘿,我正在尝试解码多级凯撒密码。我的意思是一串字母可能已经移动了几次,所以如果我说 apply_shifts[(2,3),(4,5)],这意味着我将第二个字母的所有内容都移动了 3,然后是第 4 个字母 5。这是我目前的代码。
def find_best_shifts_rec(wordlist, text, start):
"""
Given a scrambled string and a starting position from which
to decode, returns a shift key that will decode the text to
words in wordlist, or None if there is no such key.
Hint: You will find this function much easier to implement
if you use recursion.
wordlist: list of words
text: scambled text to try to find the words for
start: where to start looking at shifts
returns: list of tuples. each tuple is (position in text, amount of shift)
"""
for shift in range(27):
text=apply_shifts(text, [(start,-shift)])
#first word is text.split()[0]
#test if first word is valid. if not, go to next shift
if is_word(wordlist,text.split()[0])==False:
continue
#enter the while loop if word is valid, otherwise never enter and go to the next shift
i=0
next_index=0
shifts={}
while is_word(wordlist,text.split()[i])==True:
next_index+= len(text.split()[i])
i=i+1
#once a word isn't valid, then try again, starting from the new index.
if is_word(wordlist,text.split()[i])==False:
shifts[next_index]=i
find_best_shifts_rec(wordlist, text, next_index)
return shifts
我的问题是
1) 我的代码运行不正常,我不明白为什么会出现问题(它没有进入我的 while 循环) 和 2)我不知道如何测试我的“最终班次”(例如我的字符串的最后一部分)是否都是有效的单词,我也不知道如何从那里再次回到循环的开头.
我们将不胜感激。
【问题讨论】:
-
家庭作业?您还应该确保您的代码格式正确。看起来不是全部缩进。
-
是的,这是家庭作业。我不是要求别人为我做这件事,只是需要帮助看看我的代码有什么问题。
-
函数“is_word”是否提供给您?它看起来像什么?
-
是的,is_word(wordlist, word) 是提供给我的。它只是检查单词是否在给定的单词列表中。
标签: python