Big O算法复杂度

1. Big O介绍

大O符号(Big O notation)是用于描述函数渐进行为的数学符号。它是用另一个(通常更简单的)函数来描述一个函数数量级的渐近上界。在计算机科学中,用它来描述算法的复杂度。


2.Big O 算法复杂度

a.O(1) Constant

def func_constant(values):
    '''
    Prints first item in a list of values.
    '''
    print values[0]
    
func_constant([1,2,3])


b.O(n) Linear

def func_lin(lst):
    '''
    Takes in list and prints out all values
    '''
    for val in lst:
        print val
        
func_lin([1,2,3])


c. O(n^2) Qudratic

def func_quad(lst):
    '''
    Prints pairs for every item in list.
    '''
    for item_1 in lst:
        for item_2 in lst:
            print item_1,item_2
            
lst = [0, 1, 2, 3]

func_quad(lst)


3. Big O空间复杂度

def printer(n=10):
    '''
    Prints "hello world!" n times
    '''
    for x in range(n):
        print 'Hello World!'

这个例子就是一个O(1)的空间复杂度,因为hello world 就指定了一次, 但是这个有O(n)的算法复杂度。

你可能感兴趣的:(python算法)