CPy equivalant of functools.reduce

CircuitPython on hardware including Adafruit's boards, and CircuitPython libraries using Blinka on host computers.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
SimonDreyer
 
Posts: 7
Joined: Wed Jun 30, 2021 11:50 pm

CPy equivalant of functools.reduce

Post by SimonDreyer »

Hi Folks, is there a CircuitPython equivalent of the 'functools.reduce' function?
I have looked at Adafruit_itertools.accumulate but I'm a bit lost!
This is the line that I am trying to duplicate in CPy

s = reduce(lambda x, y: x ^ y, int_list) # Calculate the checksum

Cheers S

User avatar
dastels
 
Posts: 15820
Joined: Tue Oct 20, 2015 3:22 pm

Re: CPy equivalant of functools.reduce

Post by dastels »

You could use the definition of reduce from MicroPython's functools module:

Code: Select all

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value
Based on your example (note that ^ is xor, not exp):

Code: Select all

int_list = [2,3,4,5,6]
s = reduce(lambda x, y: x**y, int_list)
print(s)
That results in 2348542582773833227889480596789337027375682548908319870707290971532209025114608443463698998384768703031934976 which is as expected.
Dave

Locked
Please be positive and constructive with your questions and comments.

Return to “Adafruit CircuitPython”