Skip to content

Commit

Permalink
Added average absolute deviation (TheAlgorithms#5951)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
Lukasdotcom and cclauss authored Feb 13, 2022
1 parent 637cf10 commit 7a9b3c7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
29 changes: 29 additions & 0 deletions maths/average_absolute_deviation.py
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 7a9b3c7

Please sign in to comment.