0

I got stuck on that:

  • a list y = (1,2,3...)
  • a function func(A,B)
  • a constant C

How can I express this situation with loops?

B1 = func(C , y[0])
B2 = func(B1 , y[1])
B3 = func(B2 , y[2]) #.... and so on.
2
  • 2
    You can do it with looks but this is exactly what functools.reduce does. You're looking for reduce(func, [C] + y). (You need to first do from functools import reduce) Commented Jan 16, 2021 at 19:58
  • For more information see: How does reduce function work Commented Jan 16, 2021 at 20:02

2 Answers 2

2

The first argument is just the return value of the previous call, starting with C:

result = C
for yval in y:
    result = func(result, yval)

As pointed out in the comments, this pattern is captured by the often overlooked reduce function. (Overlooked, in part, because it was demoted from the built-in namespace to the functools module in Python 3.)

from functools import reduce


result = reduce(func, y, C)
Sign up to request clarification or add additional context in comments.

Comments

1

There are a few ways to do this:

First of all, regular loop:

C = ...  # the constant
b = C
for i in y:
   b = func(b, i)

But using a reduce like this, is my preferred way of doing this:

from functools import reduce
b = reduce(func, y, C)  # the last arg being the initial item used

You could also use the walrus notation, which is only useful (IMO) when saving the intermediate states.

bs = [(b := func(b, yi)) for yi in y)]
b  # b being the end result

1 Comment

For the third case, there is itertools.accumulate(y, func, initial=C).

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.