简体   繁体   中英

unsupported operand type(s) for +: 'int' and 'str' [TypeError]

I am currently learning Python so I have no idea what is going on.

    # Given N, Amount of money in the house. Adjacent houses can't be stolen. Find the max amount that can be stolen
    # 6,7,1,30,8,2,4
    numbers = input()
    n = numbers.split(",")
    t = numbers.count(",")
    def rob(nums, i):
        if i <= 0:
            return 0
        return max(rob(nums, i-2) + nums[i], rob(nums, i-1))
    print(rob(n, t))

When I run the program, entering in numbers for Num and I, it returns this:

   TypeError: unsupported operand type(s) for +: 'int' and 'str'

The values in the n array are of type 'str' , not 'int' . This is because the .split method returns type 'str' You need to convert them to 'int' in order to do the mathematical operations as you intend. Something like this:

n = [int(val) for val in n]

Put this after the line where n is initialized.

To solve the type error, you need to do as follows in the return line:

return max(rob(nums, i-2) + int(nums[i]), rob(nums, i-1))

The problem is that you are adding the return value of rob(nums, i-2) to the value nums[i] which is a string, and addition of an int to string is undefined. Note that the split function returns a list of strings (which is what n is in your code).

Furthermore, I know you were not asking about whether the algorithm works or not, but for input 30,1,1,30 your code outputs 31 , but the max that can be stolen is 60 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM