ubuntu_noob
ubuntu_noob

Reputation: 2365

Calculating the absolute minimum in list with negative numbers

I have a list like this-

list=[137,136,135,134,119,118,-14,-89,-208,-291,-491,-513,-596,-699]

Now I want to calculate the minimum number in the list irrespective of sign but in the final answer the sign should be retained.

For example here the answer would be -14.

Right now I am first splitting the list into positive and negative and calculating the minimum and maximum respectively and then comparing the absolute and returning the answer.

Upvotes: 1

Views: 1678

Answers (3)

mad_
mad_

Reputation: 8273

sorted(lst, key=lambda x: (abs(x), x))[0] # better solution would be to use min()

with key argument you can specify how it should be sorted. So in this case it will be sorted on the basis of absolute values. For example

lst = [137,136,135,134,119,118, 14, -14,-208,-291,-491,-513,-596,-699]

Then it will be sorted on the basis of abs(x) where x would be every element in the list and hence would return 14 and then -14 as absolute values of both would be 14 and there comes the role of second argument in the tuple to resolve the ties. So keeping second argument with sign will treat -14 over 14 as -14 < 14

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149796

You can use the min() function with the key argument:

>>> lst = [137,136,135,134,119,118,-14,-89,-208,-291,-491,-513,-596,-699]
>>> min(lst, key=abs)
-14

If multiple items are 'minimal' (e.g. -14 and 14), this will return the first one encountered. If you need to handle tie cases, you could use a tuple as a key, e.g.:

>>> lst = [14,137,136,135,134,119,118,-14,-89,-208,-291,-491,-513,-596,-699]
>>> min(lst, key=lambda x: (abs(x), x))
-14

Upvotes: 7

zipa
zipa

Reputation: 27869

To solve for tie cases use:

a = [137,136,135,134,119,118, 14, -14,-208,-291,-491,-513,-596,-699]
min(a, key=lambda x: (abs(x), x))
#-14

Because in this case pure abs would return 14 as it comes before.

Upvotes: 2

Related Questions