简体   繁体   English

大O符号Python功能

[英]Big O notation Python function

What is the big O of the foo(A) function (where n equals the length of A)? foo(A)函数的大O是多少 (其中n等于A的长度)? As far as i can tell the foo(4) statement is O(1) for each iteration of the recursion. 据我所知,对于每次递归迭代,foo(4)语句都是O(1)。 Also i understand that the running time of the foo(A//8) statement will be logarithmic. 我也知道foo(A // 8)语句的运行时间将是对数的。

Therefore, will the running time for the program be bigO(log(n)) ? 因此,程序的运行时间是否为bigO(log(n))?

This function is used for practicing running times for a test. 此功能用于练习测试的运行时间。

def foo(A):
    if A <= 6:
        return 7
    return foo(A//8) + foo(4)

Your program could be written as the following recurrsion: 您的程序可以编写为以下重复代码:

T(n) = T(n/8) + C

Applying Master theorem where a=1 and b=8 应用a-1b = 8的 Master定理

We fall into the second case: 我们陷入第二种情况:

n^(log(1) base 8) = n^0 = 1
C = ϴ(1). 
==> T(n) = O(n^(log(a) base b) * log(n)) = O(n^(log(1) base 8) * log(n))
         = n^0 * log(n) = 1*log(n) = O(log(n))

A is not a vector but an integer hence there is no N in this problem and the complexity must be stated in terms of A . A不是一个向量,而是一个整数,因此此问题中不存在N ,因此复杂度必须用A

Let us simulate the execution with A=1000 : 让我们模拟A=1000的执行:

foo(1000) 
    calls foo(125) and foo(4), i.e.
    calls foo(15) and foo(4), and foo(4), i.e.
    calls foo(1) and foo(4), and foo(4), and foo(4).

You get the pattern. 您得到了模式。 Thus the total number of indirect calls to foo equals the number of times you can divide A by 8 until it gets less or equal to 6 , plus the final call. 因此,对foo的间接调用的总次数等于可以将A除以8直到它小于或等于6加上最终调用的次数。

This is exactly Floor(Log8(Ceil(A/7)))+1 , which is indeed O(Log(A)) . 恰好是Floor(Log8(Ceil(A/7)))+1 ,实际上是O(Log(A))


Just for fun: 纯娱乐:

If you write A in octal (base 8), the function foo computes 7 times the sum of the octal digits but the rightmost, plus 7 or 14 (if the last digit is a 7 ). 如果用八进制数(以8为底)写A ,则函数foo计算八进制数字之和的7倍,但最右边的数字加714 (如果最后一位是7 )。

Your analysis is correct. 您的分析是正确的。 foo(4) takes constant time, and you'll have to perform the operation about log n (base 8) times - which is, of course, O(log n) . foo(4)需要固定的时间,您必须执行大约log n (以8为底)次的运算-当然,这是O(log n)

If you're more comfortable using a formula, verify with the Master Theorem (a = 1, b = 8, k = i = 0). 如果您更习惯使用公式,请通过主定理 (a = 1,b = 8,k = i = 0)进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM