3

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.

3 Answers 3

3

Its what that reduce function is for!

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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:-).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.