From 7a9b3c7292cbd71fdc7723f449b9bbcbefbf9747 Mon Sep 17 00:00:00 2001 From: Lukas Date: Sun, 13 Feb 2022 12:20:19 -0500 Subject: [PATCH] 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 --- DIRECTORY.md | 1 + maths/average_absolute_deviation.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 maths/average_absolute_deviation.py diff --git a/DIRECTORY.md b/DIRECTORY.md index e95785b25..eeea22e47 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -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) diff --git a/maths/average_absolute_deviation.py b/maths/average_absolute_deviation.py new file mode 100644 index 000000000..193d94a2f --- /dev/null +++ b/maths/average_absolute_deviation.py @@ -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()