Home > Mobile >  name ___ is not defined - recursive fibonacci memoization
name ___ is not defined - recursive fibonacci memoization

Time:09-11

NameError: name 'fib_cache' is not defined

So I am trying to implement the fibonacci number sequence using memoization, but I keep getting this error in leetcode and I am not sure why. Can anyone point me in the right direction?

class Solution:
    
    fib_cache = {}
        
    def fib(self, n: int) -> int:
        
        value;
        
        if n <=1:
            value = n;
        elif n>2:
            value = fib(n-1)   fib(n-2);
            
        fib_cache[n] = value
        return value

CodePudding user response:

I fixed some lines in your code and now it works. And actually you were not using memoization in your code so I fixed this ,too.

class Solution:
    
    fib_cache = {}
        
    def fib(self, n: int) -> int:
        
        value = 0  # You don't need this line

        if n in Solution.fib_cache:  # this adds the memoziation idea
            return Solution.fib_cache[n]

        if n <=1:
            value = n
        elif n>=2:   # <==== Fixed this line
            value = self.fib(n-1)   self.fib(n-2)   # <==== Fixed this line
            
        Solution.fib_cache[n] = value  # <==== Fixed this line
        return value

s = Solution()   # You don't need these 2 lines in leetcode
print(s.fib(5))   #  I wrote them for testing

Output: 5

  • Related