Skip to content

bugfix: Add abs_max.py & abs_min.py empty list detection #4844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion maths/abs_max.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,33 @@ def abs_max(x: list[int]) -> int:
11
>>> abs_max([3,-10,-2])
-10
>>> abs_max([])
Traceback (most recent call last):
...
ValueError: abs_max() arg is an empty sequence
"""
if len(x) == 0:
raise ValueError("abs_max() arg is an empty sequence")
j = x[0]
for i in x:
if abs(i) > abs(j):
j = i
return j


def abs_max_sort(x):
def abs_max_sort(x: list[int]) -> int:
"""
>>> abs_max_sort([0,5,1,11])
11
>>> abs_max_sort([3,-10,-2])
-10
>>> abs_max_sort([])
Traceback (most recent call last):
...
ValueError: abs_max_sort() arg is an empty sequence
"""
if len(x) == 0:
raise ValueError("abs_max_sort() arg is an empty sequence")
return sorted(x, key=abs)[-1]


Expand All @@ -32,4 +44,7 @@ def main():


if __name__ == "__main__":
import doctest

doctest.testmod(verbose=True)
main()
19 changes: 15 additions & 4 deletions maths/abs_min.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
from __future__ import annotations

from .abs import abs_val


def absMin(x):
def abs_min(x: list[int]) -> int:
"""
>>> absMin([0,5,1,11])
>>> abs_min([0,5,1,11])
0
>>> absMin([3,-10,-2])
>>> abs_min([3,-10,-2])
-2
>>> abs_min([])
Traceback (most recent call last):
...
ValueError: abs_min() arg is an empty sequence
"""
if len(x) == 0:
raise ValueError("abs_min() arg is an empty sequence")
j = x[0]
for i in x:
if abs_val(i) < abs_val(j):
Expand All @@ -17,8 +25,11 @@ def absMin(x):

def main():
a = [-3, -1, 2, -11]
print(absMin(a)) # = -1
print(abs_min(a)) # = -1


if __name__ == "__main__":
import doctest

doctest.testmod(verbose=True)
main()