def sum(list):
if list:
return list.pop() + sum(list)
return 0 def sum(list):
if list:
return list.pop() + sum(list)
return 0It is always possible to convert recursive into iterative, and most of the time doing so is trivial. I recommend doing this unless your algorithm is O(log n) or better.
def sum(li, s=0):
if len(li) == 0:
return s
else:
return sum(li[1:], li[0] + s) >>> list = [1,2,3]
>>> sum(list)/len(list)
>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zeroIt wouldn't be bad if it were obvious what it did, which it isn't with the name "sum", but would be with the name 'sum_and_empty". For good measure, maybe "sum_in_linear_space_and_empty" is even better.
It's also less efficient (although in the context of a recursive sum definition that's not too relevant). Essentially what you're doing here is using the length of the list as the iteration variable — the `i' in `for (i = n-1; i >= 0; i--)'. But `pop()' probably does more than decrement the length field, I imagine it also does some memory management bookkeeping at least.
I also take issue with how `list' is mutated and accessed in the same expression. I don't really use python, but I think I recall reading that it in fact guarantees left-to-right evaluation of such expressions. Even still, it's confusing and makes programmers, especially those who write C/C++ where this is undefined behavior, uneasy.
def sum(lst):
if lst:
return lst[0] + sum(lst[1:])
return 0And even when the type system allows you to know the input variable won't be mutated (say, passing by copy in C++), you don't know what other kinds of side-effects the function may be having.