Skip to content

Instantly share code, notes, and snippets.

@Diapolo10
Last active February 9, 2022 09:31
Show Gist options
  • Save Diapolo10/f402178257643355f6d61710a84a17c2 to your computer and use it in GitHub Desktop.
Save Diapolo10/f402178257643355f6d61710a84a17c2 to your computer and use it in GitHub Desktop.
Python functools.reduce-function example implementation
#!/usr/bin/env python3
from typing import Callable, Iterable, T
def my_reduce(func: Callable[[T, T], T], iterable: Iterable[T]) -> T:
"""
Iterates over the given iterable and feeds the values
through the given function until the iterable is
exhausted, returning the final function value.
"""
# This works on all iterables, unlike slicing or indexing
iterator = iter(iterable)
try:
result = next(iterator)
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value")
for value in iterator: # Handles StopIterations automatically
result = func(result, value)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment