Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #197539

Re: not understanding the result of functools.reduce

Path csiph.com!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail
From Ethan Carter <ec1828@somewhere.edu>
Newsgroups comp.lang.python
Subject Re: not understanding the result of functools.reduce
Date Fri, 22 Aug 2025 12:45:31 -0300
Organization A noiseless patient Spider
Lines 25
Message-ID <87ldnbnyw4.fsf@somewhere.edu> (permalink)
References <87qzx3o1md.fsf@somewhere.edu> <order-20250822162642@ram.dialup.fu-berlin.de>
MIME-Version 1.0
Content-Type text/plain
Injection-Date Fri, 22 Aug 2025 15:45:32 +0000 (UTC)
Injection-Info dont-email.me; posting-host="10712cdfb39b14d84021e67f701bda8d"; logging-data="1739963"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Q57V6IV4iAjxah16saoMmuGjxI+hCceM="
Cancel-Lock sha1:yy7Ukx5JvQp2TulAkC9YnX+dyA4= sha1:GqSSappfgYcBE8jJQwc8PiRcqXY=
Xref csiph.com comp.lang.python:197539

Show key headers only | View raw


ram@zedat.fu-berlin.de (Stefan Ram) writes:

> Ethan Carter <ec1828@somewhere.edu> wrote or quoted:
>>## The question is how to write such an operator.  I wrote this one:
>>def op(x, b):
>>  return isinstance(x, int) or b
>
>   The main snag with your op function and how you're using
>   reduce is the switch-up in the argument order that "reduce"
>   expects versus how you set up op.
>
>   "functools.reduce" calls the reducer function "op" with two
>   arguments: the accumulated value so far first, then the
>   next element from the iterable.
>
>   You wrote "op" as "op(x, b)", where you treat "x" like an element
>   and "b" like a boolean accumulator, but actually "reduce" hands
>   the accumulator first, then the element.
>
>   So when "reduce" runs, the first argument "x" is actually the boolean
>   accumulator, and the second "b" is the next element.

You're a master.  That happens to be the one thing I didn't check!  I
couldn't think of it, even though I'm well aware that not every binary
operator is commutative.  Such is life!  Thanks so much!

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar


Thread

not understanding the result of functools.reduce Ethan Carter <ec1828@somewhere.edu> - 2025-08-22 11:46 -0300
  Re: not understanding the result of functools.reduce ram@zedat.fu-berlin.de (Stefan Ram) - 2025-08-22 15:30 +0000
    Re: not understanding the result of functools.reduce Ethan Carter <ec1828@somewhere.edu> - 2025-08-22 12:45 -0300

csiph-web