![](/img/trans.png)
[英]How to fix “TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'”
[英]“TypeError: unsupported operand type(s) for +: 'int' and 'NoneType” how do I fix this this error, can you explain why it's not working
該代碼應該通過數組“A”搜索 integer“k”的實例數,然后返回該數組。 我必須使用遞歸,並且我已經使用 for 循環完成了任務。 我不確定為什么會收到此錯誤,並想了解它為什么會發生並找到解決方案。 我讀過的指南不清楚。
我已經嘗試運行 6 種代碼變體。 這不像原來的那樣優雅,但應該涵蓋所有輸入情況。
def o(k,A):
if len(A) == 1:
if A[0] == k:
return 1
else:
return
else:
if A[0] == k:
return 1 + o(k,A[1:])
else:
return o(k,A[1:])
o(5,[1,2,5,3,6,5,3,5,5,4])
我希望 function 返回 4,因為傳遞的數組中有 4 個 5 實例,但它輸出錯誤:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
def o1(k, A, count = 0):
if len(A) ==0:
return count
if (A[0] == k):
return o1(k, A[1:], count+1)
else:
return o1(k, A[1:], count)
o1(5,[1,2,5,3,6,5,3,5,5,4])
Out[1]:
4
o1(6,[1,2,5,3,6,5,3,5,5,4])
Out[2]:
1
PS 如果您僅使用遞歸,則此代碼是一種情況。 但當然,這項任務最簡化的解決方案是:
[1,2,5,3,6,5,3,5,5,4].count(5)
Out[3]:
4
def o(k,A):
if len(A) == 1:
if A[0] == k:
return 1
else:
return 0 # this explicitly value 0 helps to fixed this error. When you reached the bottom and the last element didn't match the desired value it explicitly return 0
else:
if A[0] == k:
return 1 + o(k,A[1:])
else:
return o(k,A[1:])
o(5,[1,2,5,3,6,5,3,5,5,4])
Out[12]:
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.