试图在这个Python中找到T(n)函数和复杂性

时间:2015-10-25 13:55:34

标签: python function big-o

def wum(aList):
    a = 7
    b = 5
    n = len(aList)
    for i in range(n):
        for j in range(n):
            a = i * a
            b = j * j
            w = i * j
            v = i + w
        x = v * v
        for k in range(n):
            w = a * k + 23
            v = b * b
        a = w + v

我的T(n) = 2n + 6n^2复杂度为O(n^2),这看起来是否合适?救命啊!

1 个答案:

答案 0 :(得分:1)

我总觉得为 $(function(){ $(".rating-star").mouseout(mouseOutFunction); function mouseOutFunction(){ $(".rating-star").removeClass('rating-star-on'); } $(".rating-star").click(function(e){ $(this).prevAll().andSelf().addClass('rating-star-on'); $(this).nextAll().removeClass('rating-star-on'); $(".rating-star").bind( "mouseout", mouseOutFunction); $(this).unbind( "mouseout" ); }); $(".rating-star").mouseenter(function(){ $(this).prevAll().andSelf().addClass('rating-star-on'); $(this).nextAll().removeClass('rating-star-on'); }); }); 提供一个确切的值有点困难,因为很难定义T(n)的含义。但假设这些分配中的每一项都是1(无论发生何种计算),那么总1将如下:T(n)

但是在大​​O符号中,那是n * (6n + 2) + 3,是的。您可以很容易地看到,因为您有两个嵌套的循环级别,都超过O(n²)

顺便说一下。你的功能可能是教练或其他东西的一个例子,但这确实是一个不好的例子。您可以轻松地将逻辑修改为线性并产生相同的结果:

n

由于没有任何内容使用列表中的任何值,您实际上也可以在不变的时间内进行这些计算(我会将其留给您进行练习;)。

最后,你可以争辩说,由于函数没有返回任何内容,也没有改变输入列表,函数是一个很大的NO-OP,因此可以被一个什么都不做的函数所取代: / p>

a = 7
b = 5
n = len(aList)
for i in range(n):
    a *= i ** n # `a` is multiplicated `n` times by (constant) `i`
    b = (n - 1) ** 2 # at the end of the loop, `j` is `(n - 1)`
    v = i + (i * b) # at the end of the loop, `w` is `i * b`
    x = v * v
    w = a * (n - 1) + 23 # at the end of the loop, `k` is `(n - 1)`
    v = b ** 2 # `b` (and as such `v`) is never changed in the loop
    a = w + v