我正在研究CodeFights上的一些计算机科学问题然后我发现了这个问题,起初我无法理解为什么第一种方法被认为是这种情境的最佳实现。
有人可以给我指导如何衡量Python中的关系比较编码效率吗?
if L < x ** y <= R: if x ** y > L and x ** y <= R: if x ** y in range(L + 1, R + 1):你想编写一个函数,它将整数x,y,L和R作为参数,如果xy位于区间(L,R)则返回True,否则返回False。你正在考虑几种方法在里面写一个条件语句这个功能:
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?
if L < x ** y <= R: if x ** y > L and x ** y <= R: if x ** y in range(L + 1, R + 1):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:
最满意答案
对于微型标记小片段,请查看timeit模块 。
为了记录,我强烈怀疑return L < x ** y <= R将是最有效的解决方案; 它只计算x ** y一次,短路,并且不构造其他对象。 它还直接使用测试结果,而不是使用if控制显式return True或return False 。 如果你必须选择,等同的检查将是最快的; range测试在理论上同样快,但构建range对象,即使在Py 3中,也会有很高的固定成本,而且包容测试不会弥补。
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 high fixed cost that the containment test wouldn't make up.
更多推荐
发布评论