0

I'm curious why this first function does work (OOP) but the second triggers and error. Can someone explain?

class Solution(object):
    def __init__(self):
        self.solved = {0:0,1:1,2:1}

    def fibonacci(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n in self.solved.keys():
            return self.solved[n]
        else:
            value = self.fibonacci(n-1) + self.fibonacci(n-2)

        self.solved[n] = value
        return value

t = Solution()
t.fibonacci(7)
>>> 13

But this doesn't work

found = {0:0,1:1,2:1}
def fibonacci(n):
    if n in found.keys():
        return found[n]
    else:
        value = fibonacci(n-1) + fibonacci(n-2)

    found[n] = value
    return value
fibonacci(7)
>>>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Edit: Error only found when executed on Google Colab, not in local python IDE.

mjake
  • 43
  • 1
  • 5
  • 3
    Unable to reproduce, your second example returned 13 on my machine – Cory Kramer Apr 08 '20 at 20:09
  • @CoryKramer - thanks for the comment. The error was encountered using Google Colab, however, it is not found when running python locally (I tried this once I read your comment.) I'm not sure why colab is executing differently. But it appears that's where the issues arose. – mjake Apr 08 '20 at 20:15
  • @ggorlen - thank you; I've been doing it the hard way longer than I care to admit! – mjake Apr 08 '20 at 20:16
  • 1
    @ggorlen in Python 3, `if n in found.keys()` is still bad style, but it's just as efficient as `if n in found`. – juanpa.arrivillaga Apr 08 '20 at 20:21
  • I'd guess that you've got a bogus `None` value in your `found` dictionary in the second case. In the class version you rebuild the dict for every instance, so any issue will be short-lived. – Blckknght Apr 08 '20 at 20:22
  • @juanpa.arrivillaga Hmm--you're right. Thanks. I guess the view supports O(1) `in` lookups. – ggorlen Apr 08 '20 at 21:08

0 Answers0