python dynamic array

用python 语言实现一个动态数组  类似于python内置的list

首先 必须

import ctypes

用于生成指定大小的数组

constructor,  生成一个初始容量为10,里面一个元素都没有的数组

#构造函数,创建了三个属性,分为用于指定初始容量,当前大小和当前数组
def __init__ (self):
        ‘Create an empty array.‘
        self._n = 0 #size
        self._capacity = 10
        self._A = self._make_array(self._capacity)

实现__len__函数,此函数是用于 当你使用len()函数时,会调用__len__()函数

#构造函数中创建了_n属性来指定当前大小
def __len__ (self):
        return self._n

判空

# _n指定当前大小
def is_empty(self):
        return self._n == 0

获取当前数组中的某个元素

# 因为python的数组下标可以是负数,但是这边没有进行相应的实现,有兴趣的可以自行实现
def __getitem__ (self, k):
        if not 0 <= k < self._n:
            raise ValueError(‘invalid index‘)
        return self._A[k]

追加元素

def append(self, obj):
        #当数组当前元素已满时,扩充容量为原来的两倍,在进行追加
        if self._n == self._capacity:
            self._resize(2 * self._capacity)
        self._A[self._n] = obj
        self._n += 1

创建数组和扩充数组

def _make_array(self, c):
        return (c * ctypes.py_object)( )

    def _resize(self, c):
        B = self._make_array(c)
        #扩充之后,需要将原数组中的元素copy到新数组中
        for k in range(self._n):
            B[k] = self._A[k]
        self._A = B
        self._capacity = c

在指定位置插入一个value

def insert(self, k, value):
        #当数组当前元素已满时,扩充容量为原来的两倍,在进行insert
        if self._n == self._capacity:
            self._resize(2 * self._capacity)
        for j in range(self._n, k, -1):
            self._A[j] = self._A[j-1]
        self._A[k] = value
        self._n += 1

将指定位置的元素删除

def pop(self,idx):
        if idx >= self._n:
            raise ValueError( ‘index out of bounds‘ )
        for i in range(idx,self._n - 1):
            self._A[i]=self._A[i+1]
        self._A[self._n - 1] = None
        self._n -= 1

删除指定value的元素(找到第一个就结束)

def remove(self, value):
        for k in range(self._n):
            if self._A[k] == value:
                for j in range(k, self._n - 1):
                    self._A[j] = self._A[j+1]
                self._A[self._n - 1] = None
                self._n -= 1
                return
        raise ValueError( ‘value not found‘ )

打印数组中的元素

def _print(self):
        for i in range(self._n):
            print(self._A[i], end = ‘ ‘)
        print()

测试代码:

mylist = DynamicArray()
print (‘size was: ‘, str(len(mylist)))
mylist.append(10)
mylist.append(20)
mylist.append(30)
mylist.insert(0, 0)
mylist.insert(1, 5)
mylist.insert(3, 15)
mylist._print()
mylist.remove(20)
mylist._print()

print (‘size is: ‘, str(len(mylist)))
mylist.pop(3)
mylist._print()
print (‘size is: ‘, str(len(mylist)))

测试输出

size was:  0
0 5 10 15 20 30
0 5 10 15 30
size is:  5
0 5 10 30
size is:  4

原文地址:https://www.cnblogs.com/zhanyifan/p/9746610.html

时间: 2024-11-08 17:04:13

python dynamic array的相关文章

python numpy array 与matrix 乘方

python numpy array 与matrix 乘方 编程语言 waitig 1年前 (2017-04-18) 1272℃ 百度已收录 0评论 数组array 的乘方(**为乘方运算符)是每个元素的乘方,而矩阵matrix的乘方遵循矩阵相乘,因此必须是方阵. 2*3的数组与矩阵 >>> from numpy import * >>> import operator >>> a = array([[1,2,3],[4,5,6]]) >>

python numpy array 的一些问题

1 将list转换成array 如果list的嵌套数组是不规整的,如 a = [[1,2], [3,4,5]] 则a = numpy.array(a)之后 a的type是ndarray,但是a中得元素a[i]都还是list 如果a = [[1,2], [3,4]] 则a = numpy.array(a)之后 a的type是ndarray,里面的元素a[i]也是ndarray 2 flatten函数 Python自身不带有flatten函数,numpy中array有flatten函数. 同1的一样

python数组array.array(转帖)

链接地址:https://www.cnblogs.com/sunlong88/articles/9384920.html 关于array: Python 本身没有数组这个说法, 有的就是list和tuple, list就具有其他语言中的数组特性. 至于list和tuple的区别,在于list可以在运行时修改内容和大小,tuple在首次创建和赋值后, 不可以再次修改内部的内容 不过python 有提供一个array模块,用于提供基本数字,字符类型的数组.用于容纳字符号,整型,浮点等基本类型. 这种

python two-dimensional array assignment initialize

#if you want to initialize a 9*9 two-dimensional array [([""]*9) for i in range(9)] #caution: the follow code can't work [[""]*9]*9 shallow copies of list concatenated if you change one row then the prefix row will also be changed

Leetcode刷题记录[python]——561 Array Partition I

一.前言 二.题561 Array Partition I Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Inp

python np array转json

np array转json import numpy as np import codecs, json a = np.arange(10).reshape(2,5) # a 2 by 5 array b = a.tolist() # nested lists with same data, indices file_path = "/path.json" ## your path variable json.dump(b, codecs.open(file_path, 'w', en

python multi array

''' Created on 2014-8-29 @author: hg ''' #http://www.cnblogs.com/btchenguang/archive/2012/01/30/2332479.html myList =  [[0] * 3] * 4 myList[0][1] = myList[0][1] +2 print 'shallow copy: ' for i in range(0,4):     for j in range(0,3):         print str

swig python dynamic module does not define init function

example_module = Extension('_example', sources=['example_wrap.c', 'example.c'], ) setup (name = 'example', version = '0.1', author = "SWIG Docs", description = """Simple swig example from docs""", ext_modules = [exa

LeetCode with Python -&gt; Dynamic Programming

198. House Robber You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected