Skip to content

Instantly share code, notes, and snippets.

@tnibert
Last active January 25, 2021 23:12
Show Gist options
  • Save tnibert/e140f7df20081d8edfcfcdd2183959eb to your computer and use it in GitHub Desktop.
Save tnibert/e140f7df20081d8edfcfcdd2183959eb to your computer and use it in GitHub Desktop.
Recursive reduce implementation with test
#! /usr/bin/env python3
def reduce2(func, ls):
if len(ls) == 1:
return ls[0]
return func(reduce2(func, ls[:-1]), ls[-1])
# test
testset = [1, 2, 3, 4, 5]
summation = reduce2(lambda a, x: a + x, testset)
subtr = reduce2(lambda a, x: a - x, testset)
assert summation == 15
assert subtr == -13
# compare against functools reduce
from functools import reduce
assert summation == reduce(lambda a, x: a + x, testset)
assert subtr == reduce(lambda a, x: a - x, testset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment