# code file for lecture 8, 2008 fall
#interative exponent
def exp1(a,b):
ans = 1# Initiation ans(two more step)
while (b>0):#Step1: comparsion
ans *= a#Step2: multiplication
b -= 1#Step3: subtraction
return ans# return ans(two more step)
#we need 2+3b steps go through the loop
#O(b)
#asymptotic notation
#big oh notation upper limit to growth of function as input gets large
#f(x)∈O(n*n) n measures the size of x
#recursive exponentiator
def exp2(a,b):
if b == 1:
return a
else: return a*exp2(a,b-1)
#t(b) = 3 + t(b-1) = 3 + 3 + t(b-2) = 3k + t(b-k) = 3(b-1) + 2 = 3b -1
#if you don't understand you can put b=2 in the function
#Done b-k=1 k=b-1
#O(b) liner
a = 3
b = 3
def exp3(a,b):
if b == 1:
return a
if (b%2)*2 == b:
return exp3(a*a, b/2)
else: return a*exp3(a,b-1)
#a**b = (a*a)**(b/2) b even
#a**b = (a*(a**(b-1)) b odd
#b even t(b) = 6 + t(b/2)
#b odd t(b) = 6 + t(b-1)
# = 12k + t(b/2**k)
#Done b/2**k = 1, k=logb
#O(logb)
def g(n,m):
x = 0
for i in range(n):
for j in range(m):
x += 1
return x
#O(n*m) -> m = n -> O(n**2)
#Towers of hanoi
def Towers(size, fromStack, toStack, spareStack):
if size == 1:
print ('Move disk from', fromStack, 'to', toStack)
else:
Towers(size-1, fromStack,spareStack,toStack)
Towers(1,fromStack,toStack,spareStack)
Towers(size-1,spareStack,toStack,fromStack)
#T(n) = 1 + T(1) + 2T(n-1)
#3(1+2+4+...+2**k+1)+2**n(n-k)
#O(2**n) Exponential
def search(s,e):
answer = None
i = 0
numCompares = 0
while i < len(s) and answer == None:
numCompares += 1
if e == s[i]:
answer = True
elif e < s[i]:
answer = False
i += 1
print (answer, numCompares)
def bsearch(s,e,first,last):
print (first,last)
if (last - first) < 2:
return s[first] == e or s[last] == e
mid = first + (last - first)//2
if s[mid] == e: return True
if s[mid] > e: return bsearch(s,e,first,mid - 1)
return bsearch(s,e,mid + 1,last)
def search1(s,e):
print (bsearch(s,e,0,len(s)-1))
print ('Search complete')
def testSearch():
s = range(0,1000000)
input ('basic,-1')
print (search(s,-1))
input ('binary,-1')
print (search1(s,-1))
input ('basic,end')
print (search(s,1000000))
input ('binary,end')
print (search1(s,1000000))
s = range(0,10000000)
input ('basic,partway')
print (search(s,1000000))
input ('basic,larger end')
print (search(s,10000000))
input ('binary,partway')
print (search1(s,1000000))
input ('binary,larger end')
print (search1(s,10000000))
Lecture 8: Complexity; log, linear, quadratic, exponential algorithms
最新推荐文章于 2022-04-21 16:58:34 发布