I have a Pythonic need to determine the minimum number in terms of absolute value, but preserve its sign. Below is the code I use to do this now. Is there a more elegant mechanism either mathematically or pythonically? This function is one of the most used functions in my application, so it would be nice if it were as efficient as possible in terms of interpretive overhead and mathematical calculation.
def minmag(*l):
la=map(abs,l) #store magnitudes
v=min(map(abs,l)) #find minimum magnitude
return math.copysign(v,l[la.index(v)]) #put the sign back
print minmag(5,10) #prints 5
print minmag(-5,-10) #prints -5
print minmag(-5,-10,10,-2,-1) #prints -1
P.S. I don’t care which sign is presented when there are ties in terms of equal magnitude.
You can use the
keynamed parameter ofmin:See also: documentation for the built-in function
min.