Please explain what these lines of Python code mean: def pop(self,index): if sel
ID: 3564608 • Letter: P
Question
Please explain what these lines of Python code mean:
def pop(self,index):
if self.isEmpty():
return None
size = self.size() - 1
if index > size or index < (-1 * size)-1:
return None
if index < 0:
index += size
t = self.front
print('index = ' + str(index) + ', size = ' + str(size))
if index == 0:
return self.removeFront()
if index == self.size():
return self.removeRear()
for i in range(index):
t = t.next
if t != None:
if t.next != None:
t.next.prev = t.prev
if t.prev != None:
t.prev.next = t.next
return t.data
else:
return None
Explanation / Answer
def pop(self,index): # you are defining the function
if self.isEmpty(): # checking if self(the list you have taken) is empty or not
return None # if empty then returns nothing
size = self.size() - 1 # now we initialize the value of size as size of list self minus 1
if index > size or index < (-1 * size)-1: # now we are checking if index > size or index < (-1 * size)-1
return None # if any of the two is correct then we return none
if index < 0: # now we check if index is less than 0
index += size # then we add size to index, this also means (index = index + size)
t = self.front # now we are initializing t to the first element of the loop
print('index = ' + str(index) + ', size = ' + str(size)) # now we are printing " index = (value of str(index) , size = (value of str(size))
if index == 0: # now checking if index is zero
return self.removeFront() # if index is zero then we remove the first element of the list self
if index == self.size(): # checking if index is equal to size of list self
return self.removeRear() # if so we return the value of last element of the list self.
for i in range(index): # checking if i lies in range of 0 to index
t = t.next # t will take the next value in the list
if t != None: # checking if t!= none
if t.next != None: # checking if next element of t is not equal to none
t.next.prev = t.prev #assining t as its previous
if t.prev != None: # checking if previous of t is not equal to none
t.prev.next = t.next # t becomes next of t
return t.data # return value of t
else: # if above condition does not satisfy
return None # we return none
The meaning of each line is given after #.
Feel free to ask any doubts. Have a nice day : )