count_by()
Count instances in an array based on a function's result.
Implementation
Args: array: The array to count key_func: A function that returns a grouping key Returns: A dictionary of counts by key Raises: TypeError: If array is not iterable or key_func is not callable
Example
count_by([1, 2, 3], lambda x: x % 2)
Expected output: {0: 2, 1: 1}
Source Code
def count_by(array: List[T], key_func: Callable[[T], K]) -> dict:
if not hasattr(array, "__iter__"):
raise TypeError("The 'array' parameter must be iterable.")
if not callable(key_func):
raise TypeError("The 'key_func' parameter must be callable.")
counts = {}
for item in array:
try:
key = key_func(item)
counts[key] = counts.get(key, 0) + 1
except Exception:
# Handle exceptions securely
# Optionally log the exception without exposing sensitive information
continue # Skip elements that cause exceptions
return counts