Skip to content

Commit 7d139ee

Browse files
refactor(abs): Condense abs_min and abs_max (TheAlgorithms#7881)
* refactor(abs): Condense `abs_min` and `abs_max` * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 74aa9ef commit 7d139ee

File tree

3 files changed

+66
-85
lines changed

3 files changed

+66
-85
lines changed

maths/abs.py

+66
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,62 @@ def abs_val(num: float) -> float:
1515
return -num if num < 0 else num
1616

1717

18+
def abs_min(x: list[int]) -> int:
19+
"""
20+
>>> abs_min([0,5,1,11])
21+
0
22+
>>> abs_min([3,-10,-2])
23+
-2
24+
>>> abs_min([])
25+
Traceback (most recent call last):
26+
...
27+
ValueError: abs_min() arg is an empty sequence
28+
"""
29+
if len(x) == 0:
30+
raise ValueError("abs_min() arg is an empty sequence")
31+
j = x[0]
32+
for i in x:
33+
if abs_val(i) < abs_val(j):
34+
j = i
35+
return j
36+
37+
38+
def abs_max(x: list[int]) -> int:
39+
"""
40+
>>> abs_max([0,5,1,11])
41+
11
42+
>>> abs_max([3,-10,-2])
43+
-10
44+
>>> abs_max([])
45+
Traceback (most recent call last):
46+
...
47+
ValueError: abs_max() arg is an empty sequence
48+
"""
49+
if len(x) == 0:
50+
raise ValueError("abs_max() arg is an empty sequence")
51+
j = x[0]
52+
for i in x:
53+
if abs(i) > abs(j):
54+
j = i
55+
return j
56+
57+
58+
def abs_max_sort(x: list[int]) -> int:
59+
"""
60+
>>> abs_max_sort([0,5,1,11])
61+
11
62+
>>> abs_max_sort([3,-10,-2])
63+
-10
64+
>>> abs_max_sort([])
65+
Traceback (most recent call last):
66+
...
67+
ValueError: abs_max_sort() arg is an empty sequence
68+
"""
69+
if len(x) == 0:
70+
raise ValueError("abs_max_sort() arg is an empty sequence")
71+
return sorted(x, key=abs)[-1]
72+
73+
1874
def test_abs_val():
1975
"""
2076
>>> test_abs_val()
@@ -23,6 +79,16 @@ def test_abs_val():
2379
assert 34 == abs_val(34)
2480
assert 100000000000 == abs_val(-100000000000)
2581

82+
a = [-3, -1, 2, -11]
83+
assert abs_max(a) == -11
84+
assert abs_max_sort(a) == -11
85+
assert abs_min(a) == -1
86+
2687

2788
if __name__ == "__main__":
89+
import doctest
90+
91+
doctest.testmod()
92+
93+
test_abs_val()
2894
print(abs_val(-34)) # --> 34

maths/abs_max.py

-50
This file was deleted.

maths/abs_min.py

-35
This file was deleted.

0 commit comments

Comments
 (0)