Python/maths/abs_max.py

36 lines
526 B
Python
Raw Normal View History

2019-10-05 05:14:13 +00:00
from typing import List
def abs_max(x: List[int]) -> int:
"""
>>> abs_max([0,5,1,11])
11
>>> abs_max([3,-10,-2])
-10
"""
2019-10-05 05:14:13 +00:00
j = x[0]
for i in x:
if abs(i) > abs(j):
j = i
return j
2019-10-05 05:14:13 +00:00
def abs_max_sort(x):
"""
>>> abs_max_sort([0,5,1,11])
11
>>> abs_max_sort([3,-10,-2])
-10
"""
2019-10-05 05:14:13 +00:00
return sorted(x, key=abs)[-1]
def main():
2019-10-05 05:14:13 +00:00
a = [1, 2, -11]
assert abs_max(a) == -11
assert abs_max_sort(a) == -11
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
main()