TheAlgorithms-Python
77 строк · 2.1 Кб
1"""
2Arithmetic mean
3Reference: https://en.wikipedia.org/wiki/Arithmetic_mean
4
5Arithmetic series
6Reference: https://en.wikipedia.org/wiki/Arithmetic_series
7(The URL above will redirect you to arithmetic progression)
8"""
9
10
11def is_arithmetic_series(series: list) -> bool:
12"""
13checking whether the input series is arithmetic series or not
14>>> is_arithmetic_series([2, 4, 6])
15True
16>>> is_arithmetic_series([3, 6, 12, 24])
17False
18>>> is_arithmetic_series([1, 2, 3])
19True
20>>> is_arithmetic_series(4)
21Traceback (most recent call last):
22...
23ValueError: Input series is not valid, valid series - [2, 4, 6]
24>>> is_arithmetic_series([])
25Traceback (most recent call last):
26...
27ValueError: Input list must be a non empty list
28"""
29if not isinstance(series, list):
30raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
31if len(series) == 0:
32raise ValueError("Input list must be a non empty list")
33if len(series) == 1:
34return True
35common_diff = series[1] - series[0]
36for index in range(len(series) - 1):
37if series[index + 1] - series[index] != common_diff:
38return False
39return True
40
41
42def arithmetic_mean(series: list) -> float:
43"""
44return the arithmetic mean of series
45
46>>> arithmetic_mean([2, 4, 6])
474.0
48>>> arithmetic_mean([3, 6, 9, 12])
497.5
50>>> arithmetic_mean(4)
51Traceback (most recent call last):
52...
53ValueError: Input series is not valid, valid series - [2, 4, 6]
54>>> arithmetic_mean([4, 8, 1])
554.333333333333333
56>>> arithmetic_mean([1, 2, 3])
572.0
58>>> arithmetic_mean([])
59Traceback (most recent call last):
60...
61ValueError: Input list must be a non empty list
62
63"""
64if not isinstance(series, list):
65raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
66if len(series) == 0:
67raise ValueError("Input list must be a non empty list")
68answer = 0
69for val in series:
70answer += val
71return answer / len(series)
72
73
74if __name__ == "__main__":
75import doctest
76
77doctest.testmod()
78