数组基本操作

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/14950306.html

 

class Array:
    def __init__(self, capacity):
        self.array = [None] * capacity
        self.size = 0

    def get(self, index):
        if index < 0 or index > self.size:
            raise Exception("index out of bounds")
        return self.array[index]

    def insert(self, index, data):
        if index < 0 or index > self.size:
            raise Exception("index out of bounds")
        if self.size >= len(self.array):
            self.resize()
        for i in range(self.size - 1, index - 1, -1):
            self.array[i + 1] = self.array[i]
        self.array[index] = data
        self.size += 1

    def remove(self, index):
        if index < 0 or index >= self.size:
            raise Exception("index out of bounds")
        for i in range(index, self.size - 1):
            self.array[i] = self.array[i + 1]
        self.size -= 1

    def resize(self):
        new_array = [None] * len(self.array) * 2
        for i in range(self.size):
            new_array[i] = self.array[i]
        self.array = new_array

    def output(self):
        result = ""
        for i in range(self.size):
            result += str(self.array[i]) + ", "
        return result.strip(", ")


array = Array(5)
array.insert(0, 1)
array.insert(1, 2)
array.insert(2, 3)
array.insert(3, 4)
array.insert(4, 5)
# 1, 2, 3, 4, 5
print(array.output())
# 5
print(array.get(4))
array.insert(2, 6)
array.insert(2, 7)
array.insert(2, 8)
# 1, 2, 8, 7, 6, 3, 4, 5
print(array.output())
array.remove(0)
# 2, 8, 7, 6, 3, 4, 5
print(array.output())

 

posted @ 2021-06-29 15:38  李白与酒  阅读(33)  评论(0编辑  收藏  举报