Question

Python Program Only: Write the function definition only of the "get(self, index)" function. Plug your method...

Python Program Only:

Write the function definition only of the "get(self, index)" function.

Plug your method in the code file shared with you and test it in the main to get the element at index 3 of mylist2 .

class Node:
    def __init__(self, e):
        self.element = e
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    def addFirst(self, e):
        newNode = Node(e)
        newNode.next = self.head
        self.head = newNode
        self.size = self.size + 1


    def addLast(self, e):
        newNode = Node(e)
        if self.tail == None:
            self.head = self.tail = newNode
        else:
            self.tail.next = newNode
            self.tail = self.tail.next
        self.size += 1

    def add(self, e):
        self.addLast(e)

    def insert(self, index, e):
        newNode = Node(e)
        if index == 0:
            self.addFirst(e)
        elif index >= self.size:
            self.addLast(e)
        else:
            current = self.head
            for i in range (1, index):
                current = current.next
            temp = current.next
            current.next = newNode
            (current.next).next = temp
            self.size += 1

    def removeFirst(self):
        if self.size == 0:
            return None
        else:
            temp = self.head
            self.head = self.head.next
            self.size -= 1
            if self.head == None:
                self.tail = None
            return temp.element

    def removeLast(self):
        if self.size == 0:
            return None
        elif self.size == 1:
            temp = self.head
            self.head = self.tail = None
            self.size = 0
            return temp.element
        else:
            current = self.head

            for i in range(self.size - 2):
                current = current.next

            temp = self.tail
            self.tail = current
            self.tail.next = None
            self.size -= 1
            return temp.element

    def removeAt(self, index):
        if index < 0 or index >= self.size:
            return None
        elif index == 0:
            return self.removeFirst()
        elif index == self.size - 1:
            return self.removeLast()
        else:
            previous = self.head

            for i in range(1, index):
                previous = previous.next

            current = previous.next
            previous.next = current.next
            self.size -= 1
            return current.element

    def getFirst(self):
        if self.size == 0:
            return None
        else:
            return self.head.element

    def getLast(self):
        if self.size == 0:
            return None
        else:
            return self.tail.element

    def indexOf(self, e):

        current = self.head
        i = 0

        while current != None:
            if current.element == e:
                return i
            i += 1
            current = current.next

        return -1

    def clear(self):
        self.head = None
        self.tail = None
        self.size = 0

    def contains(self, e):
        if self.indexOf(e) >= 0:
            return True
        else:
            return False


    def remove(self,e):
        index = self.indexOf(e)
        if index == -1:
            return False
        else:
            self.removeAt(index)
        return True

    def toString(self):
        result = "["

        current = self.head
        for i in range(self.size):
            result += str(current.element)
            current = current.next
            if current != None:
                result += ", "
            else:
                result += "]"

        return result

    def set(self, index, e):
        if index < 0 or index >= self.size:
            print("Index is out of range")
            return None

        current = self.head
        for i in range(index):
            current = current.next

        current.element = e

    def isEmpty(self):
        if self.size == 0:
            return True
        else:
            return False

    def getSize(self):
        return self.size

    def get(self, index): ##############I need to add this and then print it in the main function######
        return


def main():

    mylist1 = LinkedList()
    numOfElements = int(input("How many elements you want to add "))

    for i in range(numOfElements):
        print("Enter Element ", i+1," ")
        element = input()
        mylist1.add(element)

    print("Linked List mylist1 is as follows ", mylist1.toString())
    print("\n \n")


    mylist2 = LinkedList()
    listElements = input("Enter the elements you need to add seperated by white space \n")

    lista = listElements.split()


    print("Lista = ", lista, "\n")


    for e in lista:
        mylist2.add(e)

    print("Linked List mylist2 is as follows: ", mylist2.toString(), "\n")
    print("mylist2.indexOf('Detroit') is", mylist2.indexOf("Detroit"))


    print("My linked list is as follows: ",mylist2.toString())


    mylist2.remove("Dallas")
    print("Linked List after removing Dallas: ", mylist2.toString())


    mylist2.set(1,"Chicago")
    print("Linked List after setting element: ", mylist2.toString())


    if mylist2.contains("Erie"):
        print("Erie is found")
    else:
        print("Erie is not in the list")

    print("Element at index 3 of mylist 2 is: ", self.index(3)) ######## my attempt ####
main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Given below is the completed code for the question. PLEASE MAKE SURE INDENTATION IS EXACTLY AS SHOWN IN IMAGE.
Please do rate the answer if it helped. Thank you.

class Node:
   def __init__(self, e):
       self.element = e
       self.next = None

class LinkedList:
   def __init__(self):
       self.head = None
       self.tail = None
       self.size = 0

   def addFirst(self, e):
       newNode = Node(e)
       newNode.next = self.head
       self.head = newNode
       self.size = self.size + 1


   def addLast(self, e):
       newNode = Node(e)
       if self.tail == None:
           self.head = self.tail = newNode
       else:
           self.tail.next = newNode
           self.tail = self.tail.next
       self.size += 1

   def add(self, e):
       self.addLast(e)

   def insert(self, index, e):
       newNode = Node(e)
       if index == 0:
           self.addFirst(e)
       elif index >= self.size:
           self.addLast(e)
       else:
           current = self.head
           for i in range (1, index):
               current = current.next
           temp = current.next
           current.next = newNode
           (current.next).next = temp
           self.size += 1

   def removeFirst(self):
       if self.size == 0:
           return None
       else:
           temp = self.head
           self.head = self.head.next
           self.size -= 1
           if self.head == None:
               self.tail = None
           return temp.element

   def removeLast(self):
       if self.size == 0:
           return None
       elif self.size == 1:
           temp = self.head
           self.head = self.tail = None
           self.size = 0
           return temp.element
       else:
           current = self.head

           for i in range(self.size - 2):
               current = current.next

           temp = self.tail
           self.tail = current
           self.tail.next = None
           self.size -= 1
           return temp.element

   def removeAt(self, index):
       if index < 0 or index >= self.size:
           return None
       elif index == 0:
           return self.removeFirst()
       elif index == self.size - 1:
           return self.removeLast()
       else:
           previous = self.head

           for i in range(1, index):
               previous = previous.next

           current = previous.next
           previous.next = current.next
           self.size -= 1
           return current.element

   def getFirst(self):
       if self.size == 0:
           return None
       else:
           return self.head.element

   def getLast(self):
       if self.size == 0:
           return None
       else:
           return self.tail.element

   def indexOf(self, e):

       current = self.head
       i = 0

       while current != None:
           if current.element == e:
               return i
           i += 1
           current = current.next

       return -1

   def clear(self):
       self.head = None
       self.tail = None
       self.size = 0

   def contains(self, e):
       if self.indexOf(e) >= 0:
           return True
       else:
           return False


   def remove(self,e):
       index = self.indexOf(e)
       if index == -1:
           return False
       else:
           self.removeAt(index)
       return True

   def toString(self):
       result = "["

       current = self.head
       for i in range(self.size):
           result += str(current.element)
           current = current.next
           if current != None:
               result += ", "
           else:
               result += "]"

       return result

   def set(self, index, e):
       if index < 0 or index >= self.size:
           print("Index is out of range")
           return None

       current = self.head
       for i in range(index):
           current = current.next

       current.element = e

   def isEmpty(self):
       if self.size == 0:
           return True
       else:
           return False

   def getSize(self):
       return self.size

   def get(self, index):
       if index < 0 or index >= self.size:
           return None
      
       current = self.head
       for i in range(index):
           current = current.next
       return current.element


def main():

   mylist1 = LinkedList()
   numOfElements = int(input("How many elements you want to add "))

   for i in range(numOfElements):
       print("Enter Element ", i+1," ")
       element = input()
       mylist1.add(element)

   print("Linked List mylist1 is as follows ", mylist1.toString())
   print("\n \n")


   mylist2 = LinkedList()
   listElements = input("Enter the elements you need to add seperated by white space \n")

   lista = listElements.split()


   print("Lista = ", lista, "\n")


   for e in lista:
       mylist2.add(e)

   print("Linked List mylist2 is as follows: ", mylist2.toString(), "\n")
   print("mylist2.indexOf('Detroit') is", mylist2.indexOf("Detroit"))


   print("My linked list is as follows: ",mylist2.toString())


   mylist2.remove("Dallas")
   print("Linked List after removing Dallas: ", mylist2.toString())


   mylist2.set(1,"Chicago")
   print("Linked List after setting element: ", mylist2.toString())


   if mylist2.contains("Erie"):
       print("Erie is found")
   else:
       print("Erie is not in the list")

   print("Element at index 3 of mylist 2 is: ", mylist2.get(3))
main()

Add a comment
Know the answer?
Add Answer to:
Python Program Only: Write the function definition only of the "get(self, index)" function. Plug your method...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains,...

    In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains, insert, and normal_list methods. You may use default arguments and/or helper functions. The file must be named: LinkedList.py Here is what I have for my code so far. The methods I need the recursive implementations for will be bolded: class Node: """ Represents a node in a linked list (parent class) """ def __init__(self, data): self.data = data self.next = None class LinkedList: """...

  • Python 3: Write a LinkedList method named contains, that takes a value as a parameter and...

    Python 3: Write a LinkedList method named contains, that takes a value as a parameter and returns True if that value is in the linked list, but returns False otherwise. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list...

  • Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display,...

    Python 3: Python 3: Write a LinkedList class that has recursive implementations of the add, display, remove methods. You may use default arguments and/or helper functions. class Node: """ Represents a node in a linked list """ def __init__(self, data): self.data = data self.next = None class LinkedList: """ A linked list implementation of the List ADT """ def __init__(self): self.head = None def add(self, val): """ Adds a node containing val to the linked list """ if self.head is...

  • Python question. i have to start from an empty linked list, using the method addNodeEnd() to...

    Python question. i have to start from an empty linked list, using the method addNodeEnd() to add the nodes containing the values (3*i+5)%17, where i is from 0 to 10. Then print the values of all the nodes in this linked list to the screen. This is the code that i created right here and i need help checking if i made any mistakes thanks! The code is below: class Node: def __init__(self, data): self.data = data self.next = None...

  • Python code that sorts books

    class Book:    def __init__(self,id,bookName,authorName,nextNode=None):         self.id = id         self.bookName = bookName         self.authorName = authorName         self.nextNode = nextNode    def getId(self):        return self.id     def getBookName(self):        return self.bookName    def getAuthorName(self):        return self.authorName    def getNextNode(self):        return self.nextNode       def setNextNode(self,val):         self.nextNode = val   class LinkedList:    def __init__(self,head = None):         self.head = head         self.size = 0     def getSize(self):        return self.size    def AddBookToFront(self,newBook):         newBook.setNextNode(self.head)         self.head = newBook         self.size+=1     def DisplayBook(self):         curr = self.head        while curr:            print(curr.getId(),curr.getBookName(),curr.getAuthorName())              curr = curr.getNextNode()    def RemoveBookAtPosition(self,n):         prev = None         curr = self.head         curPos = 0         while curr:            if curPos == n:                if prev:                     prev.setNextNode(curr.getNextNode())                else:                     self.head = curr.getNextNode()                 self.size = self.size - 1                 return True                  prev = curr             curr = curr.getNextNode()              curPos = curPos + 1          return False     def AddBookAtPosition(self,newBook,n):         curPos = 1         if n == 0:             newBook.setNextNode(self.head)             self.head = newBook             self.size+=1             return         else:             currentNode = self.head            while currentNode.getNextNode() is not None:                if curPos == n:                     newBook.setNextNode(currentNode.getNextNode())                     currentNode.setNextNode(newBook)                     self.size+=1                     return                 currentNode = currentNode.getNextNode()                 curPos = curPos + 1             if curPos == n:                 newBook.setNextNode(None)                 currentNode.setNextNode(newBook)                 self.size+=1             else:                print("cannot add",newBook.getId(),newBook.getBookName(),"at that position")    def SortByAuthorName(self):        for i in range(1,self.size):             node1 = self.head             node2 = node1.getNextNode()            while node2 is not None:                if node1.authorName > node2.authorName:                     temp = node1.id                     temp2 = node1.bookName                     temp3 = node1.authorName                     node1.id = node2.id                     node1.bookName = node2.bookName                     node1.authorName = node2.authorName                     node2.id = temp                     node2.bookName = temp2                     node2.authorName = temp3                 node1 = node1.getNextNode()                 node2 = node2.getNextNode()     myLinkedList = LinkedList() nodeA = Book("#1","cool","Isaac") nodeB = Book("#2","amazing","Alfred") nodeC = Book("#3","hello","John") nodeD = Book("#4","why","Chase") nodeE = Book("#5","good","Mary") nodeF = Book("#6","hahaha","Radin") myLinkedList.AddBookToFront(nodeA) myLinkedList.AddBookToFront(nodeB) myLinkedList.AddBookToFront(nodeC) myLinkedList.AddBookAtPosition(nodeD,1) myLinkedList.AddBookAtPosition(nodeE,1) myLinkedList.AddBookAtPosition(nodeF,1) myLinkedList.RemoveBookAtPosition(2) myLinkedList.RemoveBookAtPosition(2) myLinkedList.DisplayBook() myLinkedList.SortByAuthorName()print(myLinkedList.getSize())...

  • If I wanted to create a method called getNum(n) that should return the data item from...

    If I wanted to create a method called getNum(n) that should return the data item from the node in the nth spot in the list. I am stuck and getting errors when I write my method. I have two files already, the first file linkedlist.py has the code .... ''' class Node(object): def __init__(self, data=None, nextNode=None): self.data = data self.nextNode = nextNode class linkedList(object): def __init__(self, head=None): self.head = head self.size = 0 def insert(self, node): if not self.head: self.head...

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • Write an implementation similar to the Priority Queue method (from chapter 26) to the linked list...

    Write an implementation similar to the Priority Queue method (from chapter 26) to the linked list using node. (from chapter 24). Your code should utilize the selectionsort method from attached and create another method call selectionsort in linkedlist class. To demonstrate the usage of the selection sort method, you should manually create a link list of random integer (say of 5 numbers), and you need to demonstrate the use the selection sort to sorted the link list. Please submit your...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT