-1

I'm trying to solve an error my code keeps generating, with the popular leet code "House Robber". How do i go about solving this. I know there are solution available, but I'm not sure what the error in the code is. Any help available will be super super helpful.

The question: https://leetcode.com/problems/house-robber/

Here's the code:

class Solution:
    def rob(self, nums: List[int]) -> int:
        
        num = [0] + nums
        
        if len(num) < 3:
            return num
        if len(num) == 3:
            return max(num)
        
        while len(num) >= 4:
            result = num[-1] + max(Solution.rob(self, nums[:len(num) - 3]),Solution.rob(self, nums[:len(num) - 2]))

            return result
                          

Here's the error:

TypeError: '>' not supported between instances of 'int' and 'list'
    result = num[-1] + max(Solution.rob(self, nums[:len(num) - 3]),Solution.rob(self, nums[:len(num) - 2]))
Line 13 in rob (Solution.py)
    result = num[-1] + max(Solution.rob(self, nums[:len(num) - 3]),Solution.rob(self, nums[:len(num) - 2]))
Line 13 in rob (Solution.py)
    ret = Solution().rob(param_1)
Line 36 in _driver (Solution.py)
    _driver()
Line 47 in <module> (Solution.py)
  • Try running through your code with a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – Alias Cartellano Mar 31 '22 at 19:24

1 Answers1

0

The problem is here

num = [0] + nums
if len(num) < 3:
  return num
if len(num) == 3:
  return max(num)

if the first condition is true then it's returning a list and for the second condition it's returning a number. As a result in your while block max() getting 2 types of data (list and int) and it can't able to compare list and int. that's why you getting that error.

while len(num) >= 4:
  result = num[-1] + max(Solution.rob(self, nums[:len(num) - 3]),Solution.rob(self, nums[:len(num) - 2]))

And a suggestion, you can write like below instead of calling

Solution.rob(self, nums[:len(num) - 3])

You can write this

self.rob(nums[:len(num) - 3])

it's more readable

atiq1589
  • 2,227
  • 1
  • 16
  • 24