Hoang Minh Nguyen
Hoang Minh Nguyen

Reputation: 91

how to call a function inside function itself in python

do we have any way to assign a function inside function itself in python? I tried to call out a nth Fibonacci as below:

memo={0:0,1:1}
def fib(n):
    if n<=1:
        return n
    if memo[n] is None:
        fib(n)=fib(n-1)+fib(n-2)
    return memo[n]

print(fib(5))

Upvotes: 1

Views: 479

Answers (2)

ShlomiF
ShlomiF

Reputation: 2895

Of course you can. It's called recursion. However, you have some errors in your code...
Try -

memo={0:0,1:1}
def fib(n):
    if n not in memo:
        memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]
        
print(fib(5))

Upvotes: 2

Yoav Glazner
Yoav Glazner

Reputation: 8066

two fixes

memo={0:0,1:1}
def fib(n):
    if n not in memo: # test
        memo[n] = fib(n-1)+fib(n-2)   # <-- set memo
    return memo[n]

print(fib(5))

Upvotes: 2

Related Questions