第一次在这里发帖,是python的新手,但我真的很喜欢我用它做的事情。正在解决麻省理工学院开放式课件的问题。有其他类似的建议吗?在
我的问题是返回一个递归函数,该函数的目的是建立一个多层移位的列表作为元组,其中每个元组都是元组(移位的起始位置,偏移量的大小)。一个5的移位会把A变成f,A-b-c-d-e-f
下面的代码供参考,但你不需要通读。在
文本是多层置乱输入,例如:“grrkxmdffi jwyxechants idchdgyqapufuelij”
def find_best_shifts_rec(wordlist, text, start):
### TODO.
"""Shifts stay in place at least until a space, so shift can only start
with a new word
Base case? all remaining words are real
Need to find the base case which goes at the start of the function to
ensure it's all cleanly returned
Base case could be empty string if true words are removed?
Base case when start = end
take recursive out of loop
use other functions to simplify
"""
shifts = []
shift = 0
for a in range(27):
shift += 1
#creates a string and only shifts from the start point
"""text[:start] + optional add in not sure how it'd help"""
testtext = apply_shift(text[start:],-shift)
testlist = testtext.split()
#counts how many real words were made by the current shift
realwords = 0
for word in testlist:
if word in wordlist:
realwords += 1
else:
#as soon as a non valid word is found i know the shift is not valid
break
if a == 27 and realwords == 0:
print 'here\'s the prob'
#if one or more words are real
if realwords > 0:
#add the location and magnitude of shift
shifts = [(start,shift)]
#recursive call - start needs to be the end of the last valid word
start += testtext.find(testlist[realwords - 1]) + len(testlist[realwords - 1]) + 1
if start >= len(text):
#Base case
return shifts
else:
return shifts + find_best_shifts_rec(wordlist,text,start)
这通常会返回正确的元组列表,但有时,以文本输入为例,我会得到错误:
^{pr2}$这个错误出现在我代码的最底层
^{3}$从我收集到的信息来看,其中一个递归调用返回None值,然后尝试将其与list进行conc会抛出错误。我怎么才能避开这个?在
编辑:
最后加上:
elif a==26: 返回[()]
当找不到正确的移位时,我可以防止输入错误。如何让整个函数返回none?在
下面是我重新编写你的代码来做你想做的事情的尝试。具体更改:删除27到26的范围,让循环自然退出并返回空的}并从零开始,因此未编码的文本将返回
shifts
数组;组合a
和{[(0, 0)]
;如果同一个单词出现在列表中两次,.find()
逻辑将混乱,将它改为rindex()
作为bandaid(也就是说,最后一个正确解码的是您想要开始的地方,而不是第一个)。在“lbh fwj hlzkv tbizljb公司”
相关问题 更多 >
编程相关推荐