reduce()
Reduce an array to a single value using a function.
Implementation
Args: array: The array to reduce func: A function that takes two arguments (accumulator, current value) initial: The initial value for the accumulator (optional) Returns: The reduced value
Example
reduce([1, 2, 3], lambda x, y: x + y, 0)
Expected output: 6
Source Code
def reduce(array: List[T], func: Callable[[U, T], U], initial: Optional[U] = None) -> U:
result = initial
for x in array:
if result is None:
result = x
else:
result = func(result, x) # type: ignore
return result # type: ignore