"""
最好情况下O(1)
最坏情况下O(n)
平均O(n)
"""defsearch(lyst,target):"""
lyst :升序序列
target :搜索目标
"""
i = 0while i < len(lyst):
if target == lyst[i]:
return i
elif target < lyst[i]:
breakelse:
i += 1return -1
第二题
"""
O(n/2)即O(n)
"""defreverse(lyst):"""
默认lyst不为空
"""
left = 0
right = len(lyst)-1while left < right:
tmp = lyst[left]
lyst[left] = lyst[right]
lyst[right] = tmp
left += 1
right -= 1return lyst
第五题
defselectionSort2(lyst, profiler, reverse = True):
i = 0while i < len(lyst) - 1: # Do n - 1 searches
thatIndex = i # for the largest
j = i + 1while j < len(lyst): # Start a search
profiler.comparison()
if reverse and lyst[j] > lyst[thatIndex]:
thatIndex = j
elifnot reverse and lyst[j] < lyst[thatIndex]:
thatIndex = j
j += 1if thatIndex != i: # Exchange if needed
swap(lyst, thatIndex, i, profiler)
i += 1
第六题
d = {}
deffib(n, dic, margin = 1):
block = "->" * margin
if n in dic:
return dic[n]
elif n < 3:
dic[n] = 1return1else:
print(block,n)
dic[n] = fib(n - 1, dic, margin + 1) + fib(n - 2, dic, margin + 1)
print(block,dic[n])
return dic[n]
print(fib(6,d))
第七题
from counter import Counter
d = {}
deffib(n, dic, counter, margin = 1):
counter.increment()
block = "->" * margin
if n in dic:
return dic[n]
elif n < 3:
dic[n] = 1return1else:
#print(block,n)
dic[n] = fib(n - 1, dic, counter, margin + 1)\
+ fib(n - 2, dic, counter, margin + 1)
#print(block,dic[n])return dic[n]
problemSize = 2
print("%12s%15s" % ("Problem Size", "Calls"))
for count in range(7):
counter = Counter()
d = {}
# The start of the algorithm
fib(problemSize,d, counter)
# The end of the algorithm
print("%12d%15s" % (problemSize, counter))
problemSize *= 2"""
终端的结果为
Problem Size Calls
2 1
4 5
8 13
16 29
32 61
64 125
128 253
复杂度为O(n)
"""
Ken Lambert著《数据结构》第三章编程项目第一题"""最好情况下O(1)最坏情况下O(n)平均O(n)"""def search(lyst,target): """ lyst :升序序列 target :搜索目标 """ i = 0 while i &lt; len(lyst): if ta