我需要一个帮助来获得一个列表中递归的>=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)
最佳答案
因为您已经在使用包装器,所以我们可以检查一个递归,它既对当前列表的奇数元素进行计数,也对列表元素进行计数。我们还可以使用索引来标记我们的位置,并避免不必要的复制(根据您的需要,此递归可以使用包装器,也可以不使用包装器):
# Returns a tuple:
# (this_list, total)
def f(L, i):
if i == len(L):
return (0,0)
this_list, total = f(L, i + 1)
if isinstance(L[i], list):
return (this_list, total + f(L[i], 0)[1])
if this_list == "list counted" or not (L[i] & 1):
return (this_list, total)
if this_list == 2:
return ("list counted", total + 1)
return (this_list + 1, total)
print f ([1, 2, 3, 5, [3, 3, 3, [5,5,5]]], 0) # ('list counted', 3)
print f ([1, 2, 3, 4, [3, 3, 3, [5,5,5]]], 0) # (2, 2)
关于python - Python:“递归”获取具有大于等于3个奇数的列表列表中的数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52303451/