TheAlgorithms-Python

Форк
0
77 строк · 2.1 Кб
1
"""
2
Arithmetic mean
3
Reference: https://en.wikipedia.org/wiki/Arithmetic_mean
4

5
Arithmetic series
6
Reference: https://en.wikipedia.org/wiki/Arithmetic_series
7
(The URL above will redirect you to arithmetic progression)
8
"""
9

10

11
def is_arithmetic_series(series: list) -> bool:
12
    """
13
    checking whether the input series is arithmetic series or not
14
    >>> is_arithmetic_series([2, 4, 6])
15
    True
16
    >>> is_arithmetic_series([3, 6, 12, 24])
17
    False
18
    >>> is_arithmetic_series([1, 2, 3])
19
    True
20
    >>> is_arithmetic_series(4)
21
    Traceback (most recent call last):
22
        ...
23
    ValueError: Input series is not valid, valid series - [2, 4, 6]
24
    >>> is_arithmetic_series([])
25
    Traceback (most recent call last):
26
        ...
27
    ValueError: Input list must be a non empty list
28
    """
29
    if not isinstance(series, list):
30
        raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
31
    if len(series) == 0:
32
        raise ValueError("Input list must be a non empty list")
33
    if len(series) == 1:
34
        return True
35
    common_diff = series[1] - series[0]
36
    for index in range(len(series) - 1):
37
        if series[index + 1] - series[index] != common_diff:
38
            return False
39
    return True
40

41

42
def arithmetic_mean(series: list) -> float:
43
    """
44
    return the arithmetic mean of series
45

46
    >>> arithmetic_mean([2, 4, 6])
47
    4.0
48
    >>> arithmetic_mean([3, 6, 9, 12])
49
    7.5
50
    >>> arithmetic_mean(4)
51
    Traceback (most recent call last):
52
        ...
53
    ValueError: Input series is not valid, valid series - [2, 4, 6]
54
    >>> arithmetic_mean([4, 8, 1])
55
    4.333333333333333
56
    >>> arithmetic_mean([1, 2, 3])
57
    2.0
58
    >>> arithmetic_mean([])
59
    Traceback (most recent call last):
60
        ...
61
    ValueError: Input list must be a non empty list
62

63
    """
64
    if not isinstance(series, list):
65
        raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
66
    if len(series) == 0:
67
        raise ValueError("Input list must be a non empty list")
68
    answer = 0
69
    for val in series:
70
        answer += val
71
    return answer / len(series)
72

73

74
if __name__ == "__main__":
75
    import doctest
76

77
    doctest.testmod()
78

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.