mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 09:10:16 +00:00
a4d68d69f1
* bugfix: Add abs_max.py & abs_min.py empty list detection * fix shebangs check
51 lines
1.0 KiB
Python
51 lines
1.0 KiB
Python
from __future__ import annotations
|
|
|
|
|
|
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 main():
|
|
a = [1, 2, -11]
|
|
assert abs_max(a) == -11
|
|
assert abs_max_sort(a) == -11
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import doctest
|
|
|
|
doctest.testmod(verbose=True)
|
|
main()
|