Skip to content

Commit 7a9b3c7

Browse files
Lukasdotcomcclauss
andauthored
Added average absolute deviation (TheAlgorithms#5951)
* Added average absolute deviation * Formats program with black * reruns updated pre commit * Update average_absolute_deviation.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 637cf10 commit 7a9b3c7

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,7 @@
454454
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
455455
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
456456
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
457+
* [Average Absolute Deviation](https://github.com/TheAlgorithms/Python/blob/master/maths/average_absolute_deviation.py)
457458
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
458459
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
459460
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)

maths/average_absolute_deviation.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def average_absolute_deviation(nums: list[int]) -> float:
2+
"""
3+
Return the average absolute deviation of a list of numbers.
4+
Wiki: https://en.wikipedia.org/wiki/Average_absolute_deviation
5+
6+
>>> average_absolute_deviation([0])
7+
0.0
8+
>>> average_absolute_deviation([4, 1, 3, 2])
9+
1.0
10+
>>> average_absolute_deviation([2, 70, 6, 50, 20, 8, 4, 0])
11+
20.0
12+
>>> average_absolute_deviation([-20, 0, 30, 15])
13+
16.25
14+
>>> average_absolute_deviation([])
15+
Traceback (most recent call last):
16+
...
17+
ValueError: List is empty
18+
"""
19+
if not nums: # Makes sure that the list is not empty
20+
raise ValueError("List is empty")
21+
22+
average = sum(nums) / len(nums) # Calculate the average
23+
return sum(abs(x - average) for x in nums) / len(nums)
24+
25+
26+
if __name__ == "__main__":
27+
import doctest
28+
29+
doctest.testmod()

0 commit comments

Comments
 (0)