【发布时间】:2015-11-14 22:03:45
【问题描述】:
起初,我不得不在没有递归的情况下做到这一点(只需通过循环,这很容易)。
现在我必须用递归来做,但我不能使用任何循环。
我想我必须用递归来遍历列表,但我不太明白我的基础应该是什么,或者减少......
def long_strings_rec(strings, N):
'''
strings - a list of strings
N - an integer
Returns all strings in 'strings' of length bigger then 'N'
(This function is recursive and does not use loops)
'''
# Your code for question #2 (second function) starts here
# Your code for question #2 (second function) ends here
有什么想法吗?我可以举个例子来说明如何使用递归对列表索引执行操作吗?
我使用了辅助函数来做到这一点,就像@7stud 建议的那样:
def helper (strings, K, results):
if len(strings) == 0:
return 0
elif len(strings[0]) > K:
results.append(strings[0])
strings.pop(0)
else:
strings.pop(0)
helper(strings, K, results)
return results
def long_strings_rec (strings, N):
'''
strings - a list of strings
N - an integer
Returns all strings in 'strings' of length bigger then 'N'
(This function is recursive and does not use loops)
'''
# Your code for question #2 (second function) starts here
return helper(strings, N, [])
# Your code for question #2 (second function) ends here
工作就像一个魅力。希望不会有问题。
【问题讨论】:
-
取列表的第一个元素,然后将列表的其余部分扔给函数本身,直到列表为空。
-
我的基础应该是什么 =>
len(strings) == 0 -
@omeinusch 尝试了您的建议。编辑了问题
-
使用所谓的 累加器 可以让事情变得更简单。让
long_strings(strings, N)做一件事:调用helper(strings, N, [])并返回该函数的结果,然后像这样定义helper():def helper(strings, N, results)。在 helper() 中,您可以将字符串附加到结果中,然后递归调用helper(strings, N, results)。但是递归是很难的,做不到也别担心。 -
我能举个例子说明如何使用递归对列表索引执行操作吗? 只需使用
pop()从字符串中删除字符串,然后如果字符串符合附加条件() 字符串到结果(上一条注释中显示的列表),然后递归调用helper(strings, N, results)
标签: python list python-2.7 recursion append