medium +20 pts

TypeVar bounded generic

Implement a generic mean function that respects type bounds.

Write a function `mean(nums)` that computes the arithmetic mean of a list of numbers (int or float). The function must be generic: use a `TypeVar` bounded to `int | float` so that static type checkers accept both `list[int]` and `list[float]` (and reject other types like `list[str]`). At runtime, it should work with any iterable of numbers and return a float. If the input list is empty, raise a `ValueError` with the message `"mean of empty iterable"`. Define the `TypeVar` inside the solution as `T = TypeVar("T", bound=int | float)`. The function signature must be `def mean(nums: list[T]) -> float:`. The implementation should use the `sum` function and the length of the list. Do not use `statistics.mean` or any external libraries.

Constraints

Input: `nums` is a list of integers or floats. It can be empty. The result is a float. Time complexity: O(n). Space complexity: O(1).

Example

>>> mean([1, 2, 3])
2.0
>>> mean([1.5, 2.5])
2.0
>>> mean([10])
10.0
>>> mean([])
Traceback (most recent call last):
...
ValueError: mean of empty iterable
>>> mean([1, 2])
1.5
20 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `sum(nums) / len(nums)` to compute the mean.
Check for empty input at the start and raise `ValueError` with the exact message.
Since the TypeVar is bound to int|float, the sum will be int or float, but dividing by len yields float.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.