Challenges in understanding efficiency of solution to a computational problem:
Goals:
drop constants and multiplicative factors
focus on dominant terms
O(n^2): n^2+ 2n + 2 - highest order n^2
O(n^2): n^2+ 100000n + 3^1000 - highest order n^2
O(n): log(n) + n + 4 - n grows faster than log(n) for large numbers
O(n log(n)): 0.0001nlog(n) + 300n - nlog(n) is higher at large values
O(3^n): 2n^30+ 3^n - 3^n is larger than n^30 at larger values
O(1) : constant
↓
O(log n) : logarithmic
↓
O(n) : linear
↓
O(n log n): loglinear
↓
O(n^c) : polynomial
↓
O(c^n) : exponential
combinecomplexity classes
Law of Addition for O():
def intToStr(i):
digits = '0123456789'
if i == 0:
return '0'
result = ''
while i > 0:
result = digits[i%10] + result
i= i//10
return result
def addDigits(s):
val= 0
for c in s:
val += int(c)
return val
def fact_iter(n):
prod = 1
for i in range(1, n+1):
prod *= i
return prod
#recusive fucntion
def fact_recur(n):
""" assume n >= 0 """
if n <= 1:
return 1
else:
return n*fact_recur(n - 1)
#iterative and recursive factorial implementations are the same order of growth
# QUADRATIC COMPLEXITY
def isSubset(L1, L2):
for e1 in L1:
matched = False
for e2 in L2:
if e1 == e2:
matched = True
break
if not matched:
return False
return True
def g(n):
""" assume n >= 0 """
x = 0
for i in range(n):
for j in range(n):
x += 1
return x
recursive functions where more than one recursive call for each size of problem
many important problems are inherently exponential
def genSubsets(L):
res = []
if len(L) == 0:
return[[]]
smaller = genSubsets(L[:-1])
extra = L[-1:]
new = []
for small in smaller:
new.append(small+extra)
return smaller+new
#Fibinnoci linear complexity _ O(n)
def fib_iter(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
fib_i= 0
fib_ii= 1
for i in range(n-1):
tmp= fib_i
fib_i= fib_ii
fib_ii= tmp+ fib_ii
return fib_ii
#Fibinnoci exponetial complexity - O(2^n)
def fib_recur(n):
""" assumes n an int>= 0 """
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib_recur(n-1) + fib_recur(n-2)
Lists: n is len(L)
Dictionaries: n is len(d)
worst case
average case
Reference