【发布时间】:2022-12-03 01:56:53
【问题描述】:
我必须创建一个递归函数来计算给定列表中有多少负值,但我无法弄清楚每个条件应该返回什么。
def countNegatives(list):
"""Takes in a list of numbers and
returns the number of negative numbers
that are inside the list."""
count = 0
if len(list) == 0:
return 0
else:
if list[0] < 0:
return count + 1
else:
return countNegatives(list[1:])
print(countNegatives([0, 1, -1, 3, -5, 6])) # should output 2 but gives me 1
print(countNegatives([-1, -3, 50,-4, -5, 1])) #should output 4 but gives me 1
【问题讨论】:
-
如何使用固定列表添加对函数的调用,以便我们可以看到所需的和实际的输出。这有助于做出有效的答案。
-
想一想,你的代码只能返回0或1,没有别的。