Last active
February 9, 2022 09:31
-
-
Save Diapolo10/f402178257643355f6d61710a84a17c2 to your computer and use it in GitHub Desktop.
Python functools.reduce-function example implementation
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
#!/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