“ TypeError:+不支持的操作数类型:'int'和'NoneType”如何解决此错误,您能否解释为什么它不起作用

时间:2019-10-20 11:26:02

标签: python

该代码应该通过数组“ A”运行,以搜索整数“ 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])

我希望函数返回4,因为传递的数组中有4个实例,值为5,但是会输出错误:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

1 个答案:

答案 0 :(得分:0)

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

P.S。如果仅使用递归,则此代码。 当然,最简化的解决方案是:

 [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