Skip to content

Commit 11792ec

Browse files
update-AM.PY
1 parent ffb7e8e commit 11792ec

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Diff for: maths/series/arithmetic_mean.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
def is_arithmetic_series(series: list) -> bool:
2+
"""
3+
checking whether the input series is arithmetic series or not
4+
5+
>>> is_arithmetic_series([2, 4, 6])
6+
True
7+
>>> is_arithmetic_series([3, 6, 12, 24])
8+
False
9+
>>> is_arithmetic_series([1, 2, 3])
10+
True
11+
12+
"""
13+
if len(series) == 1:
14+
return True
15+
common_diff = series[1] - series[0]
16+
for index in range(len(series) - 1):
17+
if series[index + 1] - series[index] != common_diff:
18+
return False
19+
return True
20+
21+
22+
def arithmetic_mean(series: list) -> float:
23+
"""
24+
return the arithmetic mean of series
25+
26+
>>> arithmetic_mean([2, 4, 6])
27+
4.0
28+
>>> arithmetic_mean([3, 6, 9, 12])
29+
7.5
30+
>>> arithmetic_mean(4)
31+
Traceback (most recent call last):
32+
...
33+
ValueError: Input series is not valid, valid series - [2, 4, 6]
34+
>>> arithmetic_mean([4, 8, 1])
35+
Traceback (most recent call last):
36+
...
37+
ValueError: Input list is not an arithmetic series
38+
>>> arithmetic_mean([1, 2, 3])
39+
2.0
40+
>>> arithmetic_mean([])
41+
Traceback (most recent call last):
42+
...
43+
ValueError: Input list must be a non empty list
44+
45+
"""
46+
if not isinstance(series, list):
47+
raise ValueError("Input series is not valid, valid series - [2, 4, 6]")
48+
if len(series) == 0:
49+
raise ValueError("Input list must be a non empty list")
50+
if not is_arithmetic_series(series):
51+
raise ValueError("Input list is not an arithmetic series")
52+
answer = 0
53+
for val in series:
54+
answer += val
55+
return answer / len(series)
56+
57+
58+
if __name__ == "__main__":
59+
import doctest
60+
61+
doctest.testmod()

0 commit comments

Comments
 (0)