[英]unsupported operand type(s) for +: 'int' and 'str' [TypeError]
I am currently learning Python so I have no idea what is going on.我目前正在学习 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))
When I run the program, entering in numbers for Num and I, it returns this:当我运行程序时,输入 Num 和 I 的数字,它会返回:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The values in the n array are of type 'str'
, not 'int'
. n 数组中的值的类型是'str'
,而不是'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.这是因为.split
方法返回类型'str'
您需要将它们转换为'int'
以便按照您的意愿进行数学运算。 Something like this:像这样的东西:
n = [int(val) for val in n]
Put this after the line where n is initialized.将其放在初始化 n 的行之后。
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.问题是您将rob(nums, i-2)
的返回值添加到作为字符串的值nums[i]
中,并且将 int 添加到字符串是未定义的。 Note that the split function returns a list of strings (which is what n
is in your code).请注意, split 函数返回一个字符串列表(这就是您的代码中的n
)。
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
.此外,我知道您不是在询问算法是否有效,而是对于输入30,1,1,30
您的代码输出31
,但可以被盗的最大值是60
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.