Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find max and min of two values

Tags:

python

I have a function that is passed two values and then iterates over the range of those values. The values can be passed in any order, so I need to find which one is the lowest first. I had the function written like this:

def myFunc(x, y):
    if x > y:
        min_val, max_val = y, x
    else:
        min_val, max_val = x, y
    for i in range(min_val, max_val):
    ...

But to save some screen space, I ended up changing it to:

def myFunc(x, y):
   min_val, max_val = sorted([x, y])
   for i in range(min_val, max_val):
   ...

How bad is this? Is there a better way that's still one line?

like image 968
Colin Avatar asked Sep 08 '10 23:09

Colin


2 Answers

min and max are your friends.

def myFunc(x, y):
    min_val, max_val = min(x, y), max(x, y)

Edit. Benchmarked min-max version againt a simple if. Due to the function call overhead, min-max takes 2.5x longer that the simple if; see http://gist.github.com/571049

like image 187
miku Avatar answered Nov 03 '22 03:11

miku


Since the OP's question was posed using x and y as parameters (not lo and hi), I would go with (for both speed and clarity):

def myfunc(x, y):
    lo, hi = (x, y) if x < y else (y, x)

>>> timeit.repeat("myfunc(10, 5)", "from __main__ import myfunc")
[1.2527812156004074, 1.185214249195269, 1.1886092749118689]
>>> timeit.repeat("foo(10, 5)", "from __main__ import foo")
[1.0397177348022524, 0.9580022495574667, 0.9673979369035806]
>>> timeit.repeat("f3(10, 5)", "from __main__ import f3")
[2.47303065772212, 2.4192818561823515, 2.4132735135754046]
like image 22
Don O'Donnell Avatar answered Nov 03 '22 04:11

Don O'Donnell