Skip to content

Commit ad76662

Browse files
haningrishashermanhui
authored andcommitted
Average mean refactor (TheAlgorithms#4485)
* Average mean refactor Added doctests and type hints to average_mean * Wiki link added * Empty list check added Empty list check added Type hint changed to typing.List
1 parent e1de0e5 commit ad76662

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

maths/average_mean.py

+21-13
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
1-
"""Find mean of a list of numbers."""
1+
from typing import List
22

33

4-
def average(nums):
5-
"""Find mean of a list of numbers."""
6-
return sum(nums) / len(nums)
7-
8-
9-
def test_average():
4+
def mean(nums: List) -> float:
105
"""
11-
>>> test_average()
6+
Find mean of a list of numbers.
7+
Wiki: https://en.wikipedia.org/wiki/Mean
8+
9+
>>> mean([3, 6, 9, 12, 15, 18, 21])
10+
12.0
11+
>>> mean([5, 10, 15, 20, 25, 30, 35])
12+
20.0
13+
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
14+
4.5
15+
>>> mean([])
16+
Traceback (most recent call last):
17+
...
18+
ValueError: List is empty
1219
"""
13-
assert 12.0 == average([3, 6, 9, 12, 15, 18, 21])
14-
assert 20 == average([5, 10, 15, 20, 25, 30, 35])
15-
assert 4.5 == average([1, 2, 3, 4, 5, 6, 7, 8])
20+
if not nums:
21+
raise ValueError("List is empty")
22+
return sum(nums) / len(nums)
1623

1724

1825
if __name__ == "__main__":
19-
"""Call average module to find mean of a specific list of numbers."""
20-
print(average([2, 4, 6, 8, 20, 50, 70]))
26+
import doctest
27+
28+
doctest.testmod()

0 commit comments

Comments
 (0)