0

I wrote this code to calculate the nth Fibonacci number and it works (calculates the right number) but fails because the table doesn't get updated. Anybody know why?

# memoization
n = 12
table = np.ones(n+1)*-1
def fib3(n):
    if table[n]==-1:
        if n<=2:
            table[n] = 1
        else:
            table[n] = fib3(n-1)+fib3(n-2)
    #return table ##This was part of my original solution but I removed it because it wasn't working
fib3(12)

This is the error I get that I think is caused by a non-updating table (since table[n] always = -1):

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
5
  • 4
    You're not actually returning anything from your function. Commented Jan 9, 2019 at 20:57
  • Your function does not return anything. So fib3(n-1) + fib3(n-2) makes no sense, because you're summing 2 void values. Commented Jan 9, 2019 at 20:57
  • aka table[n] = None + None Commented Jan 9, 2019 at 20:57
  • you need to return table[n] Commented Jan 9, 2019 at 21:01
  • Thanks for the help. I thought table was a global since it is declared outside the function Commented Jan 10, 2019 at 8:31

2 Answers 2

1

You aren't explicitly returning anything, and so your fib3 function automatically returns None. Thus your line table[n] = fib3(n-1) + fib3(n-2) evaluates to table[n] = None + None and there is no + operator defined for None.

Sign up to request clarification or add additional context in comments.

3 Comments

None is a singleton, no plural.
@TheIncorrigible1 technically correct, which is the best kind of correct! Will update. Also voted to close because it's essentially a typo.
This is the comment that most helped me understand the issue. Thanks.
0

You have missed returning the value for fib3 function

import numpy as np

# memoization
n = 12
table = np.ones(n+1)*-1
def fib3(n):
    if table[n]==-1:
        if n<=2: 
            table[n] = 1
        else:
            table[n] = fib3(n-1)+fib3(n-2)
    return table[n]
fib3(12)

144

Comments

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.