简体   繁体   中英

Python - RecursionError is inconsistently thrown

Why does Python throw a RecursionError on line 10 but not on line 13?

def fib(n, a = [0,1]):
    if len(a) > n:
        return a[n]
    a.append(fib(n - 1, a) + fib(n - 2, a))
    return a[n]


def main():
    x = 998
    print(fib(x)) # RecursionError

    for i in range(1000):
        print(fib(i)) # No Error

main()

Looking further into this, it looks like the previously mentioned mutable default argument treatment by python is actually the reason behind this. Instead of creating a new list every time the function is called, the list is created once when the function is defined.

Here is a function exploiting this feature, so that calling fib(998) doesn't throw the RecursionError:

def fib(n, a = [0,1]):
    if len(a) > n:
        return a[n]
    while len(a) <= n:
        a.append(fib(len(a) - 1) + fib(len(a) - 2))
    return a[n]

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