Python-递归-编程新手

标签 python recursion python-3.3

我需要检查numberList中的每个数字都是正数并实现以下内容 使用递归的函数。我被困住了。只是学习递归,我完全迷失了,因为我对编程非常陌生。救命!

def isEveryNumberPositiveIn(numberList):
        foundCounterexampleYet = False

        for number in numberList:
            if(number <= 0):
                foundCounterexampleYet = True
                return not(foundCounterexampleYet)

最佳答案

  1. 你的函数不是递归的,因为它从不调用自身;递归版本看起来像

    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
    
  2. 这是一个为递归函数选择的糟糕示例,因为 (a) 有一个简单的非递归解决方案,并且 (b) 向其传递一个大列表(即超过 1000 个项目)将溢出调用堆栈,并且使你的程序崩溃。相反,请尝试:

    def all_positive(lst):
        return all(i > 0 for i in lst)
    

关于Python-递归-编程新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27436170/

相关文章:

python - 如何将数据框列转置为 Pandas 中的行

python - 展平未知长度的元组

php数组递归

c++ - 递归函数是否可以在不将常量作为参数发送给它的情况下了解首次调用它的函数中的常量?

python ->> 在 float 和 int 上的 TypeError

python - python 2.x 和 3.x 之间的多线程开销差异

python - self.prepared_data 中存在多个索引字段

python - 在Python中通过selenium执行测试时,ChromeDriver应该放在哪里?

c++ - 从数字数组中查找可能的字母字符串数

python - 如何在 python 中定义一个包含 1000 位数字的十进制类?