数据结构与算法Python语言实现《Data Structures & Algorithms in Python》手写课后答案--第五章

第五章

详细介绍了动态数组的构造过程以及对其时间复杂度进行研究,深入探讨list不同情况下的效率。

本章练习偏向测试不同结构的时间效率,

代码粗糙,望大佬指出方便改进

# 5.1
def text1(n):
    import sys
    l = []
    temp = 0
    times = 0
    for i in range(n):
        size = sys.getsizeof(l)
        if temp == size:
            times += 1
        else:
            times = 0
        temp = size
        # 5.1
        '''print('length{:4d}    ,size{:4d},  repeat{:4d}'.format(
           len(l), size, times))'''
        # 5.2
        if times == 0 and len(l):
            print('每次更新数组的lenth:{:5d}'.format(len(l) - 1))
        l.append(None)
    # 5.3
    print('{:-^50}'.format('cut'))
    for i in range(n):

        size = sys.getsizeof(l)
        if temp == size:
            times += 1
        else:
            times = 0
        temp = size
        '''print('length{:4d}    ,size{:4d},  repeat{:4d}'.format(
           len(l), size, times))'''
        if times == 0 and len(l):
            print('每次更新数组的lenth:{:5d}'.format(len(l) - 1))
        l.pop()


'''改进DunamicArray'''
from TheCode.ch05.dynamic_array import DynamicArray
# 引入本地文件,该文件为教材源代码,我的博客中有提供的完整代码,第二章有路径位置


class Dynamic_array(DynamicArray):
    # 5.4
    def __getitem__(self, k):
        if k < 0:
            k = self._n + k
        if not 0 <= k < self._n:
            raise IndexError('invalid index')
        return self._A[k]
    # 5.6

    def insert(self, k, value):
        if self._n == self._capacity:
            temp = self._make_array(2 * self._capacity)
            self._capacity *= 2
            for i in range(k):
                temp[i] = self._A[i]
            temp[k] = value
            for i in range(k, self._n):
                temp[i + 1] = self._A[i]
            self._A = temp

        else:
            for i in range(self._n, k, -1):
                self._A[i] = self._A[i - 1]
            self._A[k] = value
        self._n += 1

    # 5.16
    def pop(self, index=-1):
        if index < 0:
            index = self._n + index
        if not 0 <= index < self._n:
            raise IndexError('invalid index')
        ret = self._A[index]
        if self._n < self._capacity // 4:  # 如果当前小于最大容量/4
            temp = self._make_array(self._capacity // 2)
            self._capacity //= 2
            for i in range(index):  # index之前的元素
                temp[i] = self._n[i]
            if index != self._n - 1:  # index之后的元素
                for i in range(index + 1, self._n):
                    temp[i - 1] = self._A[i]
           
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值