In: Computer Science
PYTHON - please finish the methods below that are apart of a linkedlist class #return the data value at index(position) in the list. values remain unchanged def __getpos__(self, position): #do not change, checks for valid index if self.size == 0: raise IndexError elif position is None: return self.pop(self.size - 1) elif type(position) != int: raise TypeError elif position < 0 or position >= self.size: raise IndexError #replace the data value at requested position(index). return nothing def __setpos__(self,position,value): #do not change, checks for valid index if self.size == 0: raise IndexError elif position is None: return self.pop(self.size - 1) elif type(position) != int: raise TypeError elif position < 0 or position >= self.size: raise IndexError
ANSWER:
CODE
#return the data value at index(position) in the list. values remain unchanged
def __getpos__(self, position):
#do not change, checks for valid index
if self.size == 0:
raise IndexError
elif position is None:
return self.pop(self.size - 1)
elif type(position) != int:
raise TypeError
elif position < 0 or position >= self.size:
raise IndexError
# As complete details of linkedlist class not provided,
# Assuming name of predefined variables and methods of class,
# a. self.head = gives head node of linked list
# b. node.next = gives next node attached to node
# c. node.value = gives value stored in node
# implementation
# fetching head node of linkedlist and storing in node
node = self.head
# looping for next node for (position-1) times to fetch node at required pos.
for i in range(position-1):
node = node.next
# after reaching at node of required position, returning value of the node
return node.value
#replace the data value at requested position(index). return nothing
def __setpos__(self,position,value):
#do not change, checks for valid index
if self.size == 0:
raise IndexError
elif position is None:
return self.pop(self.size - 1)
elif type(position) != int:
raise TypeError
elif position < 0 or position >= self.size:
raise IndexError
# As complete details of linkedlist class not provided,
# Assuming name of predefined variables and methods of class,
# a. self.head = gives head node of linked list
# b. node.next = gives next node attached to node
# c. node.value = gives/assigns value stored in node
# implementation
# fetching head node of linkedlist and storing in node
node = self.head
# looping for next node for (position-1) times to fetch node at required pos.
for i in range(position-1):
# node.next gives next node from node
node = node.next
# after reaching at node of required position, replacing value of the node
# using node.value for the same
node.value = value