Search code examples
pythontail-recursion

Call a Recursive method inside a class


I am trying to use tail recursion here, and I am getting Error: name 'tribonacci' is not defined

class Solution:
    def tribonacci(self, n: int) -> int:
        if (n <= 0):
            return 0
        elif (n == 1):
            return 1
        else:
            return tribonacci(n) + tribonacci(n - 1) + tribonacci(n - 2)
n=Solution()
print(n.tribonacci(4))

Solution

  • Use self keyword and also I have solved one logical error

    import functools
    class Solution:
        @functools.lru_cache(None) #memoization to avoid TLE on large input
        def tribonacci(self, n: int) -> int:
            if (n <= 0): #for -ve input
                return 0
            elif n in [1, 2]:
                return 1
            else:
                return self.tribonacci(n - 1) + self.tribonacci(n - 2) + self.tribonacci(n - 3)
    sol = Solution()
    print(sol.tribonacci(4))