Reputation: 616
is there a build-in equivalent of such function in python:
def foo(a_func,a_list):
if len(a_list)==2:
return a_func(*[a_list])
else:
return a_func(a_list[0],foo(a_func,a_list[0:]))
in other words foo(lambda x,y:x+y,[1,2,3,4])
would add 1+2+3+4
and foo(lambda x,y:x-y,[1,2,3,4])
would do ((1-2)-3)-4
etc.
And i know you can make it faster and prevent stack overflow ( :D ) but i think i remember such function but have no idea what the name is and dunno what to google.
Upvotes: 3
Views: 134
Reputation: 1122142
You are describing the reduce()
function; in Python 3 it has been moved to the functools
module:
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates((((1+2)+3)+4)+5)
.
You can of course use any callable; the operator
module offers several handy options:
>>> from functools import reduce
>>> import operator
>>> reduce(operator.add, [1,2,3,4])
10
>>> reduce(operator.sub, [1,2,3,4])
-8
Upvotes: 2
Reputation: 881705
Looks like you're looking for https://docs.python.org/2/library/functools.html#functools.reduce (AKA https://docs.python.org/2/library/functions.html#reduce in Python 2), assuming there's a bug in your code and by a_list[0:]
you actually mean a_list[1:]
(otherwise you're looking for a never-ending loop:-).
Upvotes: 2