[英]“TypeError: unsupported operand type(s) for +: 'int' and 'NoneType” how do I fix this this error, can you explain why it's not working
The code is supposed to run through an array 'A' searching for the number of insances of an integer 'k' which it then returns.该代码应该通过数组“A”搜索 integer“k”的实例数,然后返回该数组。 I have to use recursion and I've already completed the task using for loops.
我必须使用递归,并且我已经使用 for 循环完成了任务。 I'm not sure why I'm getting this error and want to understand why it's happening and find a solution.
我不确定为什么会收到此错误,并想了解它为什么会发生并找到解决方案。 The guides I've read werent clear.
我读过的指南不清楚。
I've tried running 6 variations of the code.我已经尝试运行 6 种代码变体。 This isn't as elegant as the original but should cover every case of input.
这不像原来的那样优雅,但应该涵盖所有输入情况。
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])
I would expect the function to return 4, as there are 4 instances of 5 in the array passed, but it outputs an error:我希望 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 This code in a case if you use only recursion. PS 如果您仅使用递归,则此代码是一种情况。 But of course most simplify solution for this task is:
但当然,这项任务最简化的解决方案是:
[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.