1

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))
3
  • You're trying to implement function which return n-th element of fibonacci sequence and remember all calculated items for next searches? Commented Jul 2, 2021 at 11:08
  • 1
    You call a function inside itself the same way you would call it anywhere else, but fib(n)=... wouldn't be valid anywhere, inside or outside fib. Assigning to fib(n) is not what needs to happen here. Commented Jul 2, 2021 at 11:08
  • You're trying to implement function which return n-th element of fibonacci sequence and remember all calculated items for next searches? --> yes , correct Commented Jul 2, 2021 at 11:13

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

2

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))

1 Comment

Actually, simple list will be enough for data container (demo)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.