2019-07-01 08:10:18 +00:00
|
|
|
"""Absolute Value."""
|
|
|
|
|
|
|
|
|
2022-10-12 18:41:01 +00:00
|
|
|
def abs_val(num: float) -> float:
|
2018-11-03 20:08:13 +00:00
|
|
|
"""
|
2019-07-01 08:10:18 +00:00
|
|
|
Find the absolute value of a number.
|
|
|
|
|
2019-10-21 20:36:33 +00:00
|
|
|
>>> abs_val(-5.1)
|
|
|
|
5.1
|
|
|
|
>>> abs_val(-5) == abs_val(5)
|
|
|
|
True
|
|
|
|
>>> abs_val(0)
|
2018-11-03 20:08:13 +00:00
|
|
|
0
|
|
|
|
"""
|
2019-10-08 08:24:01 +00:00
|
|
|
return -num if num < 0 else num
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2022-11-01 06:50:43 +00:00
|
|
|
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]
|
|
|
|
|
|
|
|
|
2019-10-21 20:36:33 +00:00
|
|
|
def test_abs_val():
|
|
|
|
"""
|
|
|
|
>>> test_abs_val()
|
|
|
|
"""
|
2023-03-01 16:23:33 +00:00
|
|
|
assert abs_val(0) == 0
|
|
|
|
assert abs_val(34) == 34
|
|
|
|
assert abs_val(-100000000000) == 100000000000
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2022-11-01 06:50:43 +00:00
|
|
|
a = [-3, -1, 2, -11]
|
|
|
|
assert abs_max(a) == -11
|
|
|
|
assert abs_max_sort(a) == -11
|
|
|
|
assert abs_min(a) == -1
|
|
|
|
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2022-11-01 06:50:43 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
|
|
|
|
|
|
|
test_abs_val()
|
2019-10-21 20:36:33 +00:00
|
|
|
print(abs_val(-34)) # --> 34
|