Question

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:
    """
    A linked list implementation of the List ADT (child class)
    """

    def __init__(self):
        self.head = None

    def add(self, val):
        """
        Adds a node containing val to the linked list
        """
        current = Node(val)
        if self.head is None:  # If the list is empty
            self.head = Node(val)  # Inheritance function - takes functionality from the parent class Node and allows us
            # to add the value variable
            return
        elif current.next is None:  # Reaches the end of the list
            current.next = Node(val)
            return
        else:
            self.add(current.next)  # Adds the value to the linked list
            return

    # NEEDS RECURSIVE IMPLEMENTATION
    def insert(self, val, pos):
        """
        Inserts a value into the linked list based on the number of the position
        """
        if pos == 0:  # If the position is zero, insert the new value as the new first element
            temp = self.head
            print("val:", self.head.data)
            self.head = Node(val)  # Inheritance function - takes functionality from the parent class Node and allows us
            # to add the value variable
            self.head.next = temp
        else:  # If the position is greater than zero, keep incrementing current position and insert it there or at the
            # end of the list if position > length of list
            current = self.head
            for _ in range(pos - 1):  # _ is a throwaway variable - it just indicates that the loop variable is not
                # actually used
                if current.next is None:
                    current.next = Node(val)
                    return
                current = current.next
            temp = current.next
            current.next = Node(val)
            current.next.next = temp

    # NEEDS RECURSIVE IMPLEMENTATION
    def display(self):
        """
        Prints out the values in the linked list
        """
        current = self.head
        while current is not None:
            print(current.data, end=" ")
            current = current.next
        print()

    # NEEDS RECURSIVE IMPLEMENTATION
    def remove(self, val):
        """
        Removes the node containing val from the linked list
        """
        if self.head is None:  # If the list is empty
            return

        if self.head.data == val:  # If the node to remove is the head
            self.head = self.head.next
        else:
            current = self.head
            while current is not None and current.data != val:
                previous = current
                current = current.next
            if current is not None:  # If we found the value in the list
                previous.next = current.next

    def is_empty(self):
        """
        Returns True if the linked list is empty,
        returns False otherwise
        """
        return self.head is None

    # NEEDS RECURSIVE IMPLEMENTATION
    def normal_list(self):
        """
        Returns a list of results based on the linked list
        """
        result = []
        current = self.head
        while current is not None:
            result += [current.data]
            current = current.next
        return result

    # NEEDS RECURSIVE IMPLEMENTATION
    def contains(self, key):
        """
        Returns True if that value is in the linked list,
        returns False otherwise
        """
        if self.head is None:  # If the list is empty
            return False

        current = self.head
        while current is not None:
            if current.data == key:
                return True
            current = current.next

            if current is None:
                return False

    def reverse(self):
        """
        Reverses the order of the nodes in the linked list
        """
        def reverse_recursive(cur, prev):
            """
            Recursive helper function
            """
            if not cur:   # If the base case is met
                return prev  # The return is the previous node

            # Otherwise
            nxt = cur.next
            cur.next = prev
            prev = cur
            cur = nxt
            return reverse_recursive(cur, prev)

        # Every time we call this function, it will update the state of current and previous as we go along in the
        # recursive calls to this function
        self.head = reverse_recursive(cur=self.head, prev=None)
0 0
Add a comment Improve this question Transcribed image text
Answer #1
 # Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # This function prints contents of linked list # starting from head def display(self): temp = self.head while (temp): print(temp.data) temp = temp.next # Deletes k-th node and returns new header. def remove(self,head, k) : # If invalid k if (k < 1) : return head # If linked list is empty if (head == None): return None # Base case (start needs to be deleted) if (k == 1) : res = head.next return res head.next = self.remove(head.next, k - 1) return head # Checks whether the value key # is present in linked list def contains(self, li, key): # Base case if(not li): return False # If key is present in # current node, return true if(li.data == key): return True # Recur for remaining list return self.contains(li.next, key) # This function insert a new node at # the beginning of the linked list def insert(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to # point to new Node self.head = new_node

normal_list method: Is the method that was not clear for me. Help me to understand it and what are the requirements and return value expected.

Add a comment
Know the answer?
Add Answer to:
In Python 3 Write a LinkedList class that has recursive implementations of the display, remove, contains,...
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 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 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 -------------------------------------------------------- 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...

  • 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...

  • Finish each function python 3 LList.py class node(object): """ A version of the Node class with...

    Finish each function python 3 LList.py class node(object): """ A version of the Node class with public attributes. This makes the use of node objects a bit more convenient for implementing LList class.    Since there are no setters and getters, we use the attributes directly.    This is safe because the node class is defined in this module. No one else will use this version of the class. ''' def __init__(self, data, next=None): """ Create a new node for...

  • Fill the code in list.cpp app.cpp: #include "list.hpp" int main() {         LinkedList aList; bool success =...

    Fill the code in list.cpp app.cpp: #include "list.hpp" int main() {         LinkedList aList; bool success = false;         aList.evensFrontOddsEnd(3);         aList.evensFrontOddsEnd(10);         aList.evensFrontOddsEnd(6);         aList.evensFrontOddsEnd(9);         aList.evensFrontOddsEnd(17);         aList.evensFrontOddsEnd(12);         aList.printForward(); // output should be: 12 6 10 3 9 17         aList.printBackward(); // output should be: 17 9 3 10 6 12         success = aList.remove(17); if(success) cout << "17 Successfully Removed." << endl;         success = aList.remove(10); if(success) cout << "10 Successfully Removed." << endl; success = aList.remove(7); // 7 is not in the list, so success should...

  • Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of...

    Task 2: SecretWord class: Download and save a copy of LinkedLists.py (found at the bottom of this assignment page on eClass). In this file, you have been given the complete code for a LinkedList class. Familiarize yourself with this class, noticing that it uses the Node class from Task 1 and is almost identical to the SLinkedList class given in the lectures. However, it also has a complete insert(pos, item) method (which should be similar to the insert method you...

  • 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())...

  • 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