dict as a global variable vs. dict under init

Viewed 15

I'm solving a the LeetCode question: https://leetcode.com/problems/climbing-stairs/.

If I initialize dict under init(), I can the correct cache dictionary and the problem is solved as expected, but I don't then I don't get the correct dictionary when it's just declared as a general variable.

This DOES NOT work.

class Solution:
    cache = {}

    def climb(self, i, n):
        if i in self.cache:
            return self.cache[i]
        if i > n:
            self.cache[i] = 0
            return 0
        if i == n:
            self.cache[i] = 1
            return 1
        self.cache[i] = self.climb(i + 1, n) + self.climb(i + 2, n)
        return self.cache[i]
    
    
    def climbStairs(self, n):
        return self.climb(0, n)

This works (to me, everything basically looks the same).

class Solution:
    def __init__(self):
        self.cache = {}


    def climb(self, i, n):
        if i in self.cache:
            return self.cache[i]
        if i > n:
            self.cache[i] = 0
            return 0
        if i == n:
            self.cache[i] = 1
            return 1
        self.cache[i] = self.climb(i + 1, n) + self.climb(i + 2, n)
        return self.cache[i]
    
    
    def climbStairs(self, n):
        return self.climb(0, n)
0 Answers
Related