简体   繁体   中英

Recursion error in Python function

Python code

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. Also, it will throw IndexError if your list is shorter than 50 elements because you does not set an end list condition. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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