forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmetic.py
77 lines (67 loc) · 2.12 KB
/
arithmetic.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Arithmetic mean
Reference: https://en.wikipedia.org/wiki/Arithmetic_mean
Arithmetic series
Reference: https://en.wikipedia.org/wiki/Arithmetic_series
(The URL above will redirect you to arithmetic progression)
"""
def is_arithmetic_series(series: list) -> bool:
"""
checking whether the input series is arithmetic series or not
>>> is_arithmetic_series([2, 4, 6])
True
>>> is_arithmetic_series([3, 6, 12, 24])
False
>>> is_arithmetic_series([1, 2, 3])
True
>>> is_arithmetic_series(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 6]
>>> is_arithmetic_series([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
"""
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1:
return True
common_diff = series[1] - series[0]
for index in range(len(series) - 1):
if series[index + 1] - series[index] != common_diff:
return False
return True
def arithmetic_mean(series: list) -> float:
"""
return the arithmetic mean of series
>>> arithmetic_mean([2, 4, 6])
4.0
>>> arithmetic_mean([3, 6, 9, 12])
7.5
>>> arithmetic_mean(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 6]
>>> arithmetic_mean([4, 8, 1])
4.333333333333333
>>> arithmetic_mean([1, 2, 3])
2.0
>>> arithmetic_mean([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
"""
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 0
for val in series:
answer += val
return answer / len(series)
if __name__ == "__main__":
import doctest
doctest.testmod()