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?
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
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]
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