使这变得复杂的是,你有一个双重迭代,所以有一种方法来解决这个问题,为每个循环生成一个递归函数,并将它们组合起来,这意味着一个处理内循环的辅助函数和一个处理外循环的主函数。在
为此,我们需要了解迭代函数的工作原理,一个简单的打印将有帮助def it(word):
set1 = set()
for begin in range(len(word)):
for end in range(begin,len(word)):
set1.add(word[begin:end+1])
print(word[begin:end+1])
print()
return set1
一个简单的测试揭示了一个有用的模式
^{pr2}$
这使得目标更加明确,辅助函数每次取一个字符串并删除最后一个字符或取一个更大的子字符串,而主函数将在每次递归调用中删除第一个字符。在
现在我不会给您一个工作代码,而是一个模板,它使用tail recursion,供您完成def recur_aux(word, result=None, end=None):
if result is None:
result = set()
if end is None:
end = # an adequate default value
if #an adequate stop condition, aka base case:
return result
else:
#do an adequate step
return recur_aux( word, result, #end + or - 1 )
def recur(word,result=None):
if result is None:
result = set()
if word: #this is equivalent to len(word)!=0
#do a adequate step calling recur_aux
return recur( # an adequate recursive call )
else:
return result
试一试,比如这样测试>>> it("abcdef") == recur("abcdef")