-
-
Notifications
You must be signed in to change notification settings - Fork 45.7k
/
abs.py
94 lines (78 loc) · 1.84 KB
/
abs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"""Absolute Value."""
def abs_val(num: float) -> float:
"""
Find the absolute value of a number.
>>> abs_val(-5.1)
5.1
>>> abs_val(-5) == abs_val(5)
True
>>> abs_val(0)
0
"""
return -num if num < 0 else num
def abs_min(x: list[int]) -> int:
"""
>>> abs_min([0,5,1,11])
0
>>> 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):
j = i
return j
def abs_max(x: list[int]) -> int:
"""
>>> abs_max([0,5,1,11])
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: 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]
def test_abs_val():
"""
>>> test_abs_val()
"""
assert abs_val(0) == 0
assert abs_val(34) == 34
assert abs_val(-100000000000) == 100000000000
a = [-3, -1, 2, -11]
assert abs_max(a) == -11
assert abs_max_sort(a) == -11
assert abs_min(a) == -1
if __name__ == "__main__":
import doctest
doctest.testmod()
test_abs_val()
print(abs_val(-34)) # --> 34