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'
DanGoodrick
  • 2,818
  • 6
  • 28
  • 52

2 Answers2

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.

Engineero
  • 12,340
  • 5
  • 53
  • 75
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
DanGoodrick
  • 2,818
  • 6
  • 28
  • 52