mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Add arithmetic_mean.py (#4243)
* arithmetic_mean
* arithmetic_mean
* checks
* checked
* Revert "checked"
This reverts commit 3913a39ae2
.
* checks-3
* update-1
This commit is contained in:
parent
ecf9b8164f
commit
ced83bed2c
66
maths/series/arithmetic_mean.py
Normal file
66
maths/series/arithmetic_mean.py
Normal file
|
@ -0,0 +1,66 @@
|
|||
"""
|
||||
ARITHMETIC MEAN : https://en.wikipedia.org/wiki/Arithmetic_mean
|
||||
|
||||
"""
|
||||
|
||||
|
||||
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
|
||||
"""
|
||||
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])
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Input list is not an arithmetic series
|
||||
>>> 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")
|
||||
if not is_arithmetic_series(series):
|
||||
raise ValueError("Input list is not an arithmetic series")
|
||||
answer = 0
|
||||
for val in series:
|
||||
answer += val
|
||||
return answer / len(series)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
Loading…
Reference in New Issue
Block a user