Added average absolute deviation (#5951)

* Added average absolute deviation

* Formats program with black

* reruns updated pre commit

* Update average_absolute_deviation.py

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Lukas 2022-02-13 12:20:19 -05:00 committed by GitHub
parent 637cf10555
commit 7a9b3c7292
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View File

@ -454,6 +454,7 @@
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Absolute Deviation](https://github.com/TheAlgorithms/Python/blob/master/maths/average_absolute_deviation.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)

View File

@ -0,0 +1,29 @@
def average_absolute_deviation(nums: list[int]) -> float:
"""
Return the average absolute deviation of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation
>>> average_absolute_deviation([0])
0.0
>>> average_absolute_deviation([4, 1, 3, 2])
1.0
>>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0])
20.0
>>> average_absolute_deviation([-20, 0, 30, 15])
16.25
>>> average_absolute_deviation([])
Traceback (most recent call last):
...
ValueError: List is empty
"""
if not nums: # Makes sure that the list is not empty
raise ValueError("List is empty")
average = sum(nums) / len(nums) # Calculate the average
return sum(abs(x - average) for x in nums) / len(nums)
if __name__ == "__main__":
import doctest
doctest.testmod()