Skip to content

Commit 895f536

Browse files
committed
refactor(abs): Condence abs_min and abs_max
1 parent 11e6c6f commit 895f536

File tree

3 files changed

+65
-85
lines changed

3 files changed

+65
-85
lines changed

maths/abs.py

+65
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,61 @@ def abs_val(num: float) -> float:
1313
0
1414
"""
1515
return -num if num < 0 else num
16+
17+
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+
def abs_max(x: list[int]) -> int:
38+
"""
39+
>>> abs_max([0,5,1,11])
40+
11
41+
>>> abs_max([3,-10,-2])
42+
-10
43+
>>> abs_max([])
44+
Traceback (most recent call last):
45+
...
46+
ValueError: abs_max() arg is an empty sequence
47+
"""
48+
if len(x) == 0:
49+
raise ValueError("abs_max() arg is an empty sequence")
50+
j = x[0]
51+
for i in x:
52+
if abs(i) > abs(j):
53+
j = i
54+
return j
55+
56+
57+
def abs_max_sort(x: list[int]) -> int:
58+
"""
59+
>>> abs_max_sort([0,5,1,11])
60+
11
61+
>>> abs_max_sort([3,-10,-2])
62+
-10
63+
>>> abs_max_sort([])
64+
Traceback (most recent call last):
65+
...
66+
ValueError: abs_max_sort() arg is an empty sequence
67+
"""
68+
if len(x) == 0:
69+
raise ValueError("abs_max_sort() arg is an empty sequence")
70+
return sorted(x, key=abs)[-1]
1671

1772

1873
def test_abs_val():
@@ -23,6 +78,16 @@ def test_abs_val():
2378
assert 34 == abs_val(34)
2479
assert 100000000000 == abs_val(-100000000000)
2580

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

2787
if __name__ == "__main__":
88+
import doctest
89+
90+
doctest.testmod()
91+
92+
test_abs_val()
2893
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)