[英]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.