The following list is given:
lst = [3, 7, -10]
I want to find the maximum value of absolute value. For the above list it will be 10 (abs(-10) = 10).
I can do it as follows:
max_abs_value = lst[0]
for num in lst:
if abs(num) > max_abs_value:
max_abs_value = abs(num)
What are better ways of solving this problem?
Step 1: Select a blank cell, enter the formula =MAX(ABS(A1:C4)). Step 2: Press Ctrl + Shift + Enter together, then the MAX absolute value is displayed. Step 3: Use the similar formula to get the MIN absolute value.
Python abs() The abs() function returns the absolute value of the given number. If the number is a complex number, abs() returns its magnitude.
Python abs() method returns the absolute value of the given number or list of numbers. If the number is complex, the abs() returns its magnitude. In the case of a complex number, abs() returns only the magnitude part, which can also be a floating-point number.
Using built in methods – max () and index () We can use python’s inbuilt methods to find the maximum index out of a python list. The max () method is used to find the maximum value when a sequence of elements is given. It returns that maximum element as the function output. It accepts the sequence as the function argument.
The map () function applies abs () to each number on the list, and returns a list of these absolute values, then max () finds the maximum in the list. Show activity on this post.
Python Program to find the position of min and max elements of a list using min () and max () function. Allow user to enter the length of the list. Next, iterate the for loop and add the number in the list.
The Python max () function returns the largest item in an iterable. It can also be used to find the maximum value between two or more parameters. The below example uses an input list and passes the list to max function as an argument.
The built-in max
takes a key function, you can pass that as abs
:
>>> max([3, 7, -10], key=abs)
-10
You can call abs
again on the result to normalise the result:
>>> abs(max([3, 7, -10], key=abs))
10
max(max(a),-min(a))
It's the fastest for now, since no intermediate list is created (for 100 000 values):
In [200]: %timeit max(max(a),-min(a))
100 loops, best of 3: 8.82 ms per loop
In [201]: %timeit abs(max(a,key=abs))
100 loops, best of 3: 13.8 ms per loop
In [202]: %timeit max(map(abs,a))
100 loops, best of 3: 13.2 ms per loop
In [203]: %timeit max(abs(n) for n in a)
10 loops, best of 3: 19.9 ms per loop
In [204]: %timeit np.abs(a).max()
100 loops, best of 3: 11.4 ms per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With