Insert element in an array

def insert(lst, i, e):
"""
lst:一个数组或向量,Python 就用 list 表达吧
i:待插入元素的位置
e:待插入元素
"""
##补全代码
#
  1. Subscript processing: the absolute value of positive/negative numbers is greater than the length of the array, it is added to the end and first position of the array, and the absolute value of negative numbers is less than the length of the array
    Then use index+len(list) to handle

  2. None value judgment and optimization: if the insertion position is exactly None value, then directly replace it

# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 21:51:12 2020

@author: Gary
"""

class Array(object):
    def __init__(self,lst):
        self.size=len(lst)
        self.lst=lst
    def insert(self,index,e):
        #判断数组None的个数的
        count=0
        if index<0:
            if (-index)>self.size:
                index=0
            else:
                index=index+self.size
        if index>self.size:
            index=self.size
        
        #None值判断与优化
        if self.lst[index] is None:
            self.lst[index]=e
            return self.lst
        else:
            for i in range(self.size-1,index,-1):
                if self.lst[i] is None:
                    count+=1
        if count==0: #没有None扩容数组
            self.resize()
            
        #插入数据
        for i in range(self.size-2,index-1,-1):
            if(self.lst[i] is not None)and(self.lst[i+1] is None):
                self.lst[i+1]=self.lst[i]
                self.lst[i]=None
            
        self.lst[index]=e
        return self.lst
    
    def resize(self):
        self.size=self.size*2
        lst2=[None for i in range(self.size)]
        for i in range(len(self.lst)):
            lst2[i]=self.lst[i]
        self.lst=lst2.copy()
        
if __name__=="__main__":
    my_list=[1,2,3,4,8,None]
    my_array=Array(my_list)
    my_array.insert(1,7)
    print(my_array.lst)

猜你喜欢

转载自blog.csdn.net/Garyboyboy/article/details/107326031