
[英]TypeError: unsupported operand type(s) for <<: 'str' and 'int'
[英]unsupported operand type(s) for +: 'int' and 'str' [TypeError]
我目前正在学习 Python,所以我不知道发生了什么。
# 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))
当我运行程序时,输入 Num 和 I 的数字,它会返回:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
n 数组中的值的类型是'str'
,而不是'int'
。 这是因为.split
方法返回类型'str'
您需要将它们转换为'int'
以便按照您的意愿进行数学运算。 像这样的东西:
n = [int(val) for val in n]
将其放在初始化 n 的行之后。
要解决类型错误,您需要在返回行中执行以下操作:
return max(rob(nums, i-2) + int(nums[i]), rob(nums, i-1))
问题是您将rob(nums, i-2)
的返回值添加到作为字符串的值nums[i]
中,并且将 int 添加到字符串是未定义的。 请注意, split 函数返回一个字符串列表(这就是您的代码中的n
)。
此外,我知道您不是在询问算法是否有效,而是对于输入30,1,1,30
您的代码输出31
,但可以被盗的最大值是60
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.