简体   繁体   English

递归总结列表中的元素; 蟒蛇

[英]Recursively summing up elements from a list; Python

I'm having trouble converting a recursive piece of code from Java to Python. 我在将递归代码段从Java转换为Python时遇到麻烦。 All this function does is sum up the elements in an array (or list). 此功能所做的全部工作就是汇总数组(或列表)中的元素。

public static int Summ(int [] arr, size)
{
   if(size == 0)
      return 0
   else
    return arr[size-1] + Summ(arr,size-1);

}  <-- works fine

However, in Python, I get this error message: TypeError: unsupported operand type(s) for +: 'int' and 'list'. 但是,在Python中,我收到以下错误消息:TypeError:+不支持的操作数类型:“ int”和“ list”。 Any suggestions on how to fix this problem? 关于如何解决此问题的任何建议? Thanks! 谢谢!

def Sum(arr,size):
   if size == 0:
     return 0
   else:
     return arr[size-1] + Summ(arr,size-1)

You can just use 你可以用

sum(arr)

this will return the sum of the values in the list. 这将返回列表中值的总和。

def Sum(arr,size):
   if size == 0:
     return 0
   else:
     return arr[size-1] + Sum(arr,size-1)

a=[1,2,3]  
b=Sum(a,3)
print b

Prints 6 版画6

Without seeing the Python code, it is difficult to tell exactly what is going on, but based upon the error message, your Summ method may be returning a list rather than an int. 如果不看Python代码,很难准确说明正在发生的事情,但是基于错误消息,您的Summ方法可能返回的是列表而不是int。

If the Summ object is indeed returning an int, then the arr object might actually contain a list of lists. 如果Summ对象确实返回一个int,则arr对象实际上可能包含一个列表列表。

If you really want this to be "tail" recursive: 如果您真的希望这是“尾巴”递归:

def Sum(lst):
    if not lst:
        raise ValueError("Summing an empty iterable?  That's nonsense")
    return lst[0]+Sum(lst[1:]) if len(lst) > 1 else lst[0]

but the builtin sum function is definitely a better bet -- It'll work for any iterable and it will be more efficient and there's no chances of ever hitting the recursion limit using it. 但是内建的sum函数绝对是一个更好的选择-它将可用于任何可迭代的函数,并且效率更高,并且没有机会使用它来达到递归限制。

Python's not really built for tail recursion the way many other languages are. Python不是像其他语言一样真正为尾部递归而构建的。 Guido seems to think that it's not worth worrying about since you can always just re-code it as a loop. Guido似乎认为这不值得担心,因为您始终可以将其重新编码为循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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