我需要检查numberList
中的每个数字都是正数并实现以下内容
使用递归的函数。我被困住了。只是学习递归,我完全迷失了,因为我对编程非常陌生。救命!
def isEveryNumberPositiveIn(numberList):
foundCounterexampleYet = False
for number in numberList:
if(number <= 0):
foundCounterexampleYet = True
return not(foundCounterexampleYet)
最佳答案
你的函数不是递归的,因为它从不调用自身;递归版本看起来像
def all_positive(lst): if lst: return lst[0] > 0 and all_positive(lst[1:]) # ^ # this is the recursive bit - # the function calls itself else: return True # this keeps the function from looping forever - # when it runs out of list items, it stops calling itself
这是一个为递归函数选择的糟糕示例,因为 (a) 有一个简单的非递归解决方案,并且 (b) 向其传递一个大列表(即超过 1000 个项目)将溢出调用堆栈,并且使你的程序崩溃。相反,请尝试:
def all_positive(lst): return all(i > 0 for i in lst)
关于Python-递归-编程新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27436170/