-2

I need help with defining an add function in python. This is my first time writing in python so I have trouble with a lot of the formatting. I need to define an add function for an arraylist that shifts one position all the items j>=i, insert an element at position i of the list and increment the number of elements in the list Inputs: i: Index that is integer non negative and at most n x: Object type, i.e., any object This is what I have written so far:

def add(self, i : int, x : object) :
    if i>0 & i<self.size():

        for n in range(i, self.size())

    else:
        pass 

Now I wrote some psuedocode and was wondering if it would work:

def(add(self, i : int, x : object) :
  declare new empty array of size n+1
 if i>0 and i<=n:
   for(i to arr length):
    put i into new array
 else:
  pass

3 Answers3

2

so, basically python has this built in.

mylist.insert(index, element)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

so much trouble for something already built-in D:

lst.insert(index, element)
Ironkey
  • 2,568
  • 1
  • 8
  • 30
1
def __init__(self, iitems):
    self.items = iitems
    self.size = len(self.items)

def add(self, i, x):
    ret = self.items[:i]
    ret.append(x)
    ret.extend(self.items[i:])
    self.items = ret
    self.size += 1
Suspended
  • 1,184
  • 2
  • 12
  • 28