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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值