python数据结构----数组

1. 一维数组

Array类使用python列表来保存其项,常用的魔法方法包括初始化(__init__)、求其长度(__len__)、字符串表示(__str__)、迭代(__iter__)、获取指定位置的值(__getitem__)、设置指定位置的值(__setitem__)

数组的操作主要有:增加数组的长度、减小数组的长度、在数组中插入新的一项、从数组中删除一项。

1)      增加数组大小:如果逻辑大小和物理大小相等,此时就要增加物理大小,在时间复杂和空间复杂度中折衷中,我们选择将物理大小调整为原来的两倍,然后创建一个新的数组,并且将旧的数组中的值拷贝到新的数组当中,最后将旧的数组变量重置为新的数组变量。

2)      减小数组大小:条件为:装载因子要小于预设的值(如0.25)同时现在数组的物理大小要为默认值的两倍以上。装载因子为逻辑大小和物理大小的比值。如果满足条件,将物理大小减少一半,后续步骤和增加数组的步骤一样。

3)      在数组中插入新的一项:在插入之前要先判断是否有可用空间,其次从数组的末尾开始直至目标位置,将每一项后移一个单元,然后见空余的目标位置填入新的值,最后将逻辑大小加1

4)      在数组中删除一项:从紧跟目标索引位置之后的位置开始,到数组的逻辑末尾,将每一项都向前移动一位;然后将逻辑大小减1;最后判断是否需要减小数组大小。

Code:

class Array(object):
   
def __init__(self, capacity, fillValue=None):
       
self.items= list()
       
for i in range(capacity):
           
self.items.append(fillValue)

   
def __len__(self):
       
"""len of the array"""
       
return len(self.items)

   
def __str__(self):
       
"""string representation of thearray"""
       
return str(self.items)

   
def __iter__(self):
       
"""iter of thr array"""
       
return iter(self.items)

   
def __getitem__(self, index):
       
"""get item of the array atindex"""
       
return self.items[index]

   
def __setitem__(self, index, newValue):
       
"""set new value of the array at index"""
       
self.items[index]= newValue

def main():
   
DEFAULT_CAPACITY = 5
   
logicalSize = 0
   
a = Array(DEFAULT_CAPACITY)
   
for i in range(len(a)):
    
   a[i] = i + 1
       
logicalSize += 1
   
print(a)
   
"""
   
Increase size of array:
    now logical equal to default capacity
    so if you want to add item into array
    you should increase capacity of array
    """
    if logicalSize== DEFAULT_CAPACITY:
       
temp = Array(len(a) * 2)             # create a new Array
       
for i in range(logicalSize):
           
temp[i] = a[i]                   # copy data from the old
       
a = temp
   
print(a)

   
"""
   
Insert an item into  array
    first, check out the logical size ofarray
    second, remove item until targetindex
    third, set value at index
    last, logical size add 1
    """
    targetIndex= 3
   
newValue = 6
   
if logicalSize< len(a):
       
for i in range(logicalSize, targetIndex, -1):
           
a[i] = a[i-1]
       
a[targetIndex] = newValue
        logicalSize += 1
   
# elif: firstly Increase size of array, secondly run theprevious step
   
print(a)

   
"""
   
Delete item in array at index
    first, remove item
    second. logical size sub 1
    third, check out the load factor
    """
    targetIndex = 4
   
for i in range(targetIndex, logicalSize):
       
a[i] = a[i+1]
   
logicalSize -= 1
   
print(a)

   
# in order to illustrate the decrease size of array, we delete some items
    targetIndex = 1
   
for j in range(3):
       
for i in range(targetIndex, logicalSize):
           
a[i] = a[i+1]
       
logicalSize -= 1
   
print(a)

   
"""
   
Decrease size of array
    first, judge the condition, create anew array
    second, copy data from old array tonew
    third, assignment
    """
    if logicalSize<= len(a)//4 and len(a) >= DEFAULT_CAPACITY * 2:
       
temp = Array(len(a) // 2)
       
for i in range(logicalSize):
           
temp[i] = a[i]
        a = temp
    print(a)

if __name__ == "__main__":
   
main()

2. 二维数组

要创建一个Grid(网格,也值二维数组)对象,可以以3个参数来运行Grid构造方法,即高度、宽度、填充值。需要有初始化函数,获取二维数组的高度和宽度,以及获取索引位置的值,以及打印数组等函数。

code:

class Grid(object):
    """representation a two dimensional array"""
    def __init__(self, rows, cols, fillValue=None):
        self.data = Array(rows)
        for i in range(rows):
            self.data[i] = Array(cols, fillValue)

    def getHeight(self):
        """ return the number of cols """
        return len(self.data)

    def getWidth(self):
        """return the number of rows"""
        return len(self.data[0])

    def __getitem__(self, index):
        """support two-dimensional indexing with [row][col]"""
        return self.data[index]

    def __str__(self):
        """return a string representation of the grid"""
        result = ""
        for row in range(self.getHeight()):
            for col in range(self.getWidth()):
                result += str(self.data[row][col]) + ' '
            result += "\n"
        return result

3 三维数组

可以将三维数组可视化的表示为:一个盒子中装满了较小的盒子,小盒子按照行和列整齐的堆叠,在创建该数组的时候,给定它的深度、高度和宽度,所以三维数组可由一维数组和二维数组共同组成。

Code:

lass threeDimensionalArray(object):
    """representation three dimensional array"""
    def __init__(self, depth, row, col, fillValue=None):
        self.data = Array(depth)
        for i in range(depth):
            self.data[i] = Grid(row, col, fillValue)

    def __getitem__(self, index):
        return self.data[index]

    def getDepth(self):
        """return the depth of three dimensional array"""
        return len(self.data)

    def getHeight(self):
        """return the row of three dimensional array"""
        return self.data[0].getHeight()

    def getWidth(self):
        """return the col of three dimensional array"""
        return self.data[0].getWidth()


你可能感兴趣的:(python)