python - 递归地对列表的元素求和

标签 python algorithm recursion divide-and-conquer

def sum(L):
    if len(L) == 1:
        return L[0]
    i = sum (len (L) // 2)
    if  len(L) > 1:
        return i + i

L=[2,4]

print (sum(L))

当我尝试运行它时出现 TypeError: object of type 'int' has no len()。

最佳答案

sum (len (L)//2) 中,您传递一个整数(len(L)//2 的结果)作为 L 参数到您的 sum() 函数。 (请不要为函数提供与内置函数相同的名称。)递归调用的 sum() 然后尝试计算 len(L) == 1这个整数,但整数不支持 len(),因此您会收到有问题的错误消息。您到底想做什么?

关于python - 递归地对列表的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003564/

相关文章:

algorithm - mergesort 是 O(n) 的归纳证明有什么问题?

javascript - 从父子 JSON 数据中获取所有子项

recursion - 为什么这个拆分功能有效?

python - 使用 Pyodbc + UnixODBC + FreeTDS 设置连接设置

python - 如何用sklearn获得所有三个SVD矩阵?

algorithm - 寻找多个多边形的公共(public)轮廓

python - 斐波那契递归树 -Python-

python - 编写此递归函数的更多 pythonic 方式

c# - 在 Python 中使用 C# DLL

python - 在 Beam 管道中以编程方式生成 BigQuery 架构