[英]Time complexity of a simple Python function
I have been given a simply Python programme as such:我得到了一个简单的 Python 程序,如下所示:
def boo(n):
if n == 1:
return 1
else:
return boo(n/2) + boo(n/2)
To boo, I have to find out the time complexity of the function.嘘,我必须找出函数的时间复杂度。 My idea is that since each
n
makes a call to two more boo
's, the time complexity is O(2^n)
.我的想法是,由于每个
n
都会调用另外两个boo
,因此时间复杂度为O(2^n)
。 However, it has been revealed that this is wrong.然而,事实证明这是错误的。 The answer has been revealed to me that the actual time complexity is O(n) without rationale given.
答案已经告诉我,实际的时间复杂度是 O(n),没有给出基本原理。 My hunch is that
boo(n/2) + boo(n/2)
can be treated as 2*boo(n/2)
, but I am highly suspicious of this as I have seen similar scenarios before, and I vaguely remember that boo(n/2) + boo(n/2)
cannot be equated to 2*boo(n/2)
in terms of processing steps.我的预感是
boo(n/2) + boo(n/2)
可以被视为2*boo(n/2)
,但我对此非常怀疑,因为我之前见过类似的情况,我依稀记得boo(n/2) + boo(n/2)
不能等同于2*boo(n/2)
在处理步骤方面。
What would be a more appropriate way to understand this?什么是更合适的方式来理解这一点? I am still struggling with the ideas in order of growth (space and time complexity), so if anyone has any general advice or material that can possibly help me, I greatly welcome them.
我仍在按增长顺序(空间和时间复杂性)努力解决这些想法,所以如果有人有任何可能对我有帮助的一般性建议或材料,我非常欢迎他们。 Thank you very much!
非常感谢!
This code is O(∞)
, as a non-power-of-two input will never complete (it will go from > 1
to < 1
without ever being == 1
).这段代码是
O(∞)
,因为非 2 的幂输入永远不会完成(它将从> 1
到< 1
而不是== 1
)。
For powers of 2 (or if properly rewritten to do boo(n // 2)
and not recurse infinitely), it's O(n)
, as each step halves the input, but then does that halved work twice, leading to overall linear performance (to be precise, boo
is called 2n - 1
times for n
being a power of 2).对于 2 的幂(或者如果正确重写以执行
boo(n // 2)
而不是无限递归),它是O(n)
,因为每一步都将输入减半,但是这会减半两次,从而导致整体线性性能(准确地说,因为n
是 2 的幂,所以boo
被称为2n - 1
次)。 Changing the final line to return boo(n // 2) * 2
would get it to O(log n)
performance.将最后一行更改为
return boo(n // 2) * 2
将使其达到O(log n)
性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.