Ken Lambert著《数据结构》第三章编程项目

Ken Lambert著《数据结构》第三章编程项目

第一题

"""
最好情况下O(1)
最坏情况下O(n)
平均O(n)
"""
def search(lyst,target):
    """
    lyst :升序序列
    target :搜索目标
    """
    i = 0 
    while i < len(lyst):
        if target == lyst[i]:
            return i
        elif target < lyst[i]:
            break
        else:
            i += 1
    return -1

第二题

"""
O(n/2)即O(n)
"""
def reverse(lyst):
    """
    默认lyst不为空
    """
    left = 0
    right = len(lyst)-1
    while left < right:
        tmp = lyst[left]
        lyst[left] = lyst[right]
        lyst[right] = tmp
        left += 1
        right -= 1
    return lyst

第五题

def selectionSort2(lyst, profiler, reverse = True):
    i = 0
    while i < len(lyst) - 1:         # Do n - 1 searches
        thatIndex = i                 # for the largest
        j = i + 1                    
        while j < len(lyst):         # Start a search
            profiler.comparison()
            if reverse and lyst[j] > lyst[thatIndex]:
                thatIndex = j
            elif not reverse and lyst[j] < lyst[thatIndex]:
                thatIndex = j
            j += 1
        if thatIndex != i:            # Exchange if needed
            swap(lyst, thatIndex, i, profiler)
        i += 1

第六题

d = {}
def fib(n, dic, margin = 1):
    block = "->" * margin
    if n in dic:
        return dic[n]
    elif n < 3:
        dic[n] = 1
        return 1
    else:
        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 = {}
def fib(n, dic, counter, margin = 1):
    counter.increment()
    block = "->" * margin
    if n in dic:
        return dic[n]
    elif n < 3:
        dic[n] = 1
        return 1
    else:
        #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)
"""
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值