Re: not understanding the result of functools.reduce

Ethan Carter <[email protected]>
Newsgroups gmane.comp.python.general
Organization A noiseless patient Spider
Message-ID <[email protected]>
[email protected] (Stefan Ram) writes:

> Ethan Carter <[email protected]> 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!
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.