Skip to content

Instantly share code, notes, and snippets.

@marcuscaisey
Last active March 21, 2019 22:47
Show Gist options
  • Save marcuscaisey/3c96c03b502389625cccfa3422a55b2f to your computer and use it in GitHub Desktop.
Save marcuscaisey/3c96c03b502389625cccfa3422a55b2f to your computer and use it in GitHub Desktop.
reduce implemented recursively and iteratively
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