forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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 <cclauss@me.com>
- Loading branch information
1 parent
637cf10
commit 7a9b3c7
Showing
2 changed files
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |