繁体   English   中英

“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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM