Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi please helppp and no I don\'t want another answer that\'s copy pasted from th

ID: 3719990 • Letter: H

Question

Hi please helppp and no I don't want another answer that's copy pasted from the textbook. What's wrong with my get_node method? Implementing linked list in python. Currently, my set item method it only works for positiove indices but for negative index say a_list[-2]=2if a_list= [1,2] it will return none type has no attribute item? Problem seems to be in my get node method for negative indices?

def _get_node(self, index):
        if index>=0:
            if index >=len(self):
                raise IndexError( "Positiove index out of range")
            node=self.head
            for _ in range(index):
                node=node.next
       
        elif index<0:

**Changes here**


            if index<-1*len(self):
                raise IndexError("Negative index out of range")
            node=self.head
            for _ in range(index,-1*(len(self)+1),-1):
                node=node.next

        return node

********************************

My set item method

def __setitem__(self, index,item):
        if index>0 and index>=len(self):
            raise IndexError("Positive index out of range")

        elif index<0 and index<-1*len(self):
            raise IndexError("Negative index out of range")
        if index==0:
            self.head.item=item

        else:
            node=self._get_node(index)
            node.item=item

Explanation / Answer

You've written

node=node.next


but there is no "node" object defined hence it is a 'NoneType' object. The only time you define it is in the if statement above it but essentially if you go into the else statement you haven't created a node object to perform node.next

The relationship between negative indices and positive indices are positive indices-len(self)=negative indices so all you have to change is


for _ in range(index, 0 ,1):
node=self._get_node(index+len(self))

Any confusion feel free to comment below.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote