I'm working on some Computer Science problems on CodeFights and then I found this problem, At first I couldn't understand why the first approach is considered as the best implementation for this context.
Can someone give me guidance on how to measure the relational comparison coding efficiency in Python?
You would like to write a function that takes integer numbers x, y, L and R as parameters and returns True if xy lies in the interval (L, R] and False otherwise. You're considering several ways to write a conditional statement inside this function:
if L < x ** y <= R:
if x ** y > L and x ** y <= R:
if x ** y in range(L + 1, R + 1):
For microbenchmarking small snippets, take a look at the timeit
module.
For the record, I strongly suspect return L < x ** y <= R
will be the most efficient solution; it computes x ** y
only once, short-circuits, and constructs no additional objects. It also uses the result of the test directly, rather than using if
checks controlling explicit return True
or return False
. The equivalent if
check would be the fastest if you have to choose; range
tests are equally fast in theory, but constructing the range
object, even in Py 3, would have a higher fixed cost that the containment test wouldn't make up.