python 一个简单模拟 list 的动态列表

# encoding=UTF-8

import ctypes


class DynamicArray:
    """a dynamic array class akin to a simplified python list"""

    def __init__(self):
        """create an empty array"""
        self._n = 0                                     # count actual elements
        self._capacity = 1                              # default array capacity
        self._A = self._make_array(self._capacity)      # low-level array

    def __len__(self):
        """return number of elements stored in the array"""
        return self._n

    def __getitem__(self, k):
        """return element at index k"""
        if not 0 <= k < self._n:
            raise IndexError('invalid index')
        return self._A[k]                               # retrieve from array

    def append(self, obj):
        """add object to end of the array"""
        print('arr len:', self._capacity)
        if self._n == self._capacity:                   # not enough room
            self._resize(2 * self._capacity)            # so double capacity
        self._A[self._n] = obj
        self._n += 1

    def insert(self, k, value):
        """insert value at index k, shifting subsequent values rightward"""
        # (for simplicity, we assume 0<=k<=n in this version)
        if self._n == self._capacity:                   # not enough room
            self._resize(2 * self._capacity)            # so duble capacity
        for j in range(self._n, k, -1):                 # shift rightmost first
            self._A[j] = self._A[j-1]
        self._A[k] = value                              # store newest element
        self._n += 1

    def remove(self, value):
        """remove first occurrence of value (or raise valueError)"""
        # note: we do not consider shrinking the dynamic array in this version
        for k in range(self._n):
            if self._A[k] == value:                     # found a match
                for j in range(k, self._n-1):           # shift others to fill gap
                    self._A[j] = self._A[j+1]
                self._A[self._n-1] = None               # help garbage collection
                self._n -= 1                            # we have one less item
                return                                  # exit immediately
        raise ValueError('value not found')             # only reached if not match

    def _resize(self, c):                               # nonpublic utitity
        """resize internal array to capacity c"""
        B = self._make_array(c)                         # new (bigger) array
        for k in range(self._n):                        # for each existing value
            B[k] = self._A[k]
        self._A = B                                     # use the bigger array
        self._capacity = c

    def _make_array(self, c):                           # nonpublic utitity
        """return new array with capacity c"""
        return (c * ctypes.py_object)()                 # see ctypes documentation
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值