File size: 1,534 Bytes
eee346e
 
 
 
 
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
 
 
 
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
 
 
 
 
696363c
eee346e
 
696363c
eee346e
 
696363c
eee346e
 
 
 
696363c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Mathematical utility functions."""

from typing import List, Union

Number = Union[int, float]


def calculate_mean(numbers: List[Number]) -> float:
    """Calculate the arithmetic mean of a list of numbers.

    Args:
        numbers: A list of integers or floating point numbers

    Returns:
        float: The arithmetic mean of the input numbers

    Raises:
        ValueError: If the input list is empty
        TypeError: If any element is not a number
    """
    if not numbers:
        raise ValueError("Cannot calculate mean of empty list")

    if not all(isinstance(x, (int, float)) for x in numbers):
        raise TypeError("All elements must be numbers")

    return sum(numbers) / len(numbers)


def calculate_median(numbers: List[Number]) -> float:
    """Calculate the median value from a list of numbers.

    Args:
        numbers: A list of integers or floating point numbers

    Returns:
        float: The median value of the input numbers

    Raises:
        ValueError: If the input list is empty
        TypeError: If any element is not a number
    """
    if not numbers:
        raise ValueError("Cannot calculate median of empty list")

    if not all(isinstance(x, (int, float)) for x in numbers):
        raise TypeError("All elements must be numbers")

    sorted_numbers = sorted(numbers)
    length = len(sorted_numbers)

    if length % 2 == 0:
        mid = length // 2
        return (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2
    else:
        return sorted_numbers[length // 2]