简体   繁体   English

Python函数中的递归错误

[英]Recursion error in Python function

Python code Python代码

def find(*num): 
    i =0
    if num[i] != None:
        print(num[i])
        return find(i+1)

Result 结果

RecursionError: maximum recursion depth exceeded in comparison

How can I stop at the end of index? 如何停止索引的结尾?

It looks like you're trying to print the value of the last (positional) argument passed to the function. 似乎您正在尝试打印传递给该函数的最后一个(位置)参数的值。

This should work: 这应该工作:

def find(*num): 
    print(num[-1])

You end up with error because you did not set "recursion end" condition. 由于未设置“递归结束”条件,因此最终会出错。 Basically what you have to add is something like: 基本上,您必须添加以下内容:

def find(*nums):
    if <your condition>:
        return

    ... logic ...

It is hard to say what exactly should be there, since I don't quite understand what you are trying to accomplish. 很难说到底应该有什么,因为我不太了解您要完成什么。

Your function will throw RecursionError every time when your list is 50 elements or longer because that is default recursion depth in python. 每当列表等于或大于50个元素时,函数都会抛出RecursionError,因为这是python中的默认递归深度。 Also, it will throw IndexError if your list is shorter than 50 elements because you does not set an end list condition. 另外,如果您的列表少于50个元素,则由于未设置结束列表条件,它将引发IndexError。 If you want to print all numeric elements in list, you could use a single loop: 如果要打印列表中的所有数字元素,可以使用一个循环:

def find (*num):
    for entry in num:
        if entry is not None:
            print (entry)

if you absolutely wanted a recursion solution, then you need to modify recursion depth and resourse used and add exit condition: 如果您绝对需要递归解决方案,则需要修改递归深度和使用的资源并添加退出条件:

import resource, sys
//be wary, your memory usage could went waaay up
resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))
sys.setrecursionlimit(10**6)

def find (*num):
    if len(num)==0: 
        return None
    current, tail = num[0], num[1:]
    if current is not None: 
        print (current)
    find (tail)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM