Last active
March 21, 2019 22:47
-
-
Save marcuscaisey/3c96c03b502389625cccfa3422a55b2f to your computer and use it in GitHub Desktop.
reduce implemented recursively and iteratively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def reduce(function, sequence, initial=None): | |
i = iter(sequence) | |
try: | |
initial = initial if initial is not None else next(i) | |
except StopIteration: | |
raise TypeError("reduce() of empty sequence with no initial value") | |
try: | |
return reduce(function, i, function(initial, next(i))) | |
except StopIteration: | |
return initial | |
def reduce(function, sequence, initial=None): | |
i = iter(sequence) | |
try: | |
result = initial if initial is not None else next(i) | |
except StopIteration: | |
raise TypeError("reduce() of empty sequence with no initial value") | |
for x in i: | |
result = function(result, x) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment