Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional way to replace reduce()

In Python 3, reduce() has been moved to functools.reduce() and apparently it's better to use list comprehensions or plain loops for better readability.

I want to print the XOR'ed value of all elements in a list.

# My implementation with functools
from functools import reduce
print(reduce(lambda a, b: a^b, [1, 3, 2, 3, 4, 4, 5, 2, 1]))

And I have this:

# My implementation without functools
def XOR(x):
    ans = 0
    for i in x:
        ans = ans ^ i
    return ans

print(XOR([1, 3, 2, 3, 4, 4, 5, 2, 1]))

How can write a more functional version of this code without reduce()?

(Please provide references or code in Python 3, if any.)

like image 671
Ajit Panigrahi Avatar asked Oct 19 '25 13:10

Ajit Panigrahi


1 Answers

Although Guido van Rossum didn't much care for reduce(), enough of the community did want it, which is why it was moved to functools and not removed outright. It is performant, and ideally suited to your use case. Just use it.

You can make your case faster and more readable by using operator.xor() to avoid the overhead of a new Python frame for a lambda:

from functools import reduce
from operator import xor

reduce(xor, [1, 3, 2, 3, 4, 4, 5, 2, 1])

Both xor() and reduce() are implemented in C. Calling back to the Python interpreter loop for the lambda is quite slow compared to calling another C function.

If you really must use a function, then use

def xor_reduce(values):
    result = 0
    for value in values:
        result ^= value
    return result

using in-place XOR, and better variable names.

like image 85
Martijn Pieters Avatar answered Oct 21 '25 03:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!