Skip to content

Commit 5b874a6

Browse files
committed
To Add Arithmetic Mean function in maths/series
1 parent 3cea941 commit 5b874a6

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
The Arithmetic Mean of n numbers is defined as the sum of the numbers
3+
divided by n. It is used to measure the central tendency of the numbers.
4+
https://en.wikipedia.org/wiki/Arithmetic_mean
5+
"""
6+
7+
8+
def compute_arithmetic_mean(*args: float) -> float:
9+
"""
10+
Return the arithmetic mean of the argument numbers.
11+
If invalid input is provided, it prints an error message and returns None.
12+
13+
>>> compute_arithmetic_mean(1, 2, 3, 4, 5)
14+
3.0
15+
>>> compute_arithmetic_mean(5, 10)
16+
7.5
17+
>>> compute_arithmetic_mean('a', 69)
18+
'Error: Not a Number'
19+
>>> compute_arithmetic_mean()
20+
'Error: At least one number is required'
21+
>>> compute_arithmetic_mean(2.5, 3.5, 4.0)
22+
3.3333333333333335
23+
"""
24+
try:
25+
if len(args) == 0:
26+
raise ValueError("At least one number is required")
27+
28+
total = 0
29+
count = 0
30+
for number in args:
31+
if not isinstance(number, (int, float)):
32+
raise TypeError("Not a Number")
33+
total += number
34+
count += 1
35+
36+
return total / count
37+
38+
except (TypeError, ValueError) as error:
39+
return f"Error: {error}"
40+
41+
42+
if __name__ == "__main__":
43+
from doctest import testmod
44+
45+
testmod(name="compute_arithmetic_mean")
46+
print(compute_arithmetic_mean(1, 2, 3, 4, 5))
47+
print(compute_arithmetic_mean('a', 69))
48+
print(compute_arithmetic_mean())

0 commit comments

Comments
 (0)