【发布时间】:2019-02-17 14:00:08
【问题描述】:
我需要帮助以递归方式获取 >= 3 个奇数的列表列表。例如, [1, 2, 3, 4, [3, 3, 3]] 返回 1,因为只有内部列表有超过 3 个奇数。 [2, 5, 5, 5, [3, 3, 3]] 返回 2,因为外循环和内循环都有超过 3 个奇数。
对我来说最困难的部分是跟踪计算奇数个数的条件。所以我想出了一个想法,在每个递归步骤中使用一个额外的参数(cnt)。
底部的伪代码不起作用,这只是我的基本想法。有人可以给我一些提示或想法吗?
def count_even(L):
def helper(L, cnt):
if L is empty return 0
elif cnt == 3 return 1 # when odd numbers >= 3 then it returns
elif L[0] is even? return helper(L[0], count+1) # increment cnt
elif L[0] is list? # if detects inner loop, then another recursion
inner_list = L[0]
return helper(inner_list[0], 0) + helper(inner_list[1:], 0)
else: # L[0] is not even
return helper(L[1:], count)
# calling a helper function with cnt=0
helper(L, 0)
【问题讨论】:
-
在这里尝试使用递归深度优先搜索方法。每当你遇到
list,调用递归函数,然后调用你的helper函数来计算连续的奇数。
标签: python algorithm recursion