简体   繁体   中英

Recursively summing up elements from a list; Python

I'm having trouble converting a recursive piece of code from Java to 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'. 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

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.

If the Summ object is indeed returning an int, then the arr object might actually contain a list of lists.

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.

Python's not really built for tail recursion the way many other languages are. Guido seems to think that it's not worth worrying about since you can always just re-code it as a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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