Question

In: Computer Science

Please add the following method as a part of the UnorderedList class definition: •print_list: the method...

Please add the following method as a part of the UnorderedList class definition:

•print_list:

the method prints the elements of the

list using the same format as a Python list

(square brackets and commas as separators).

In the main function of the modified UnorderedList.py, please test the new method to demonstrate that it works as expected.

Please leave comments in the code to show what is done

UnorderList.py file

# Implementation of an Unordered List ADT as a linked list. The list

# is accessed through a reference to the first element, head.  

# Adopted from Section 3.9 of the textbook.

from Node import Node

class UnorderedList:

  '''

  List is empty upon creation and the head reference is None

  '''

  def __init__(self):

    self.head = None   

     

  '''

  Returns True if list is empty, False otherwise

  '''

  def is_empty(self):

    return self.head == None

   

  '''

  Add an element to head of the list

  '''

  def add(self, item):

    # Create a node using item as its data

    temp = Node(item)

    # make the next reference of the new node refer to the head

    # of the list

    temp.set_next(self.head)

    # modify the list head so that it references the new node

    self.head = temp

     

  '''

  Returns the size of the list

  '''

  def size(self):

    # start at the head of the list

    current = self.head

    count = 0

    # Traverse the list one element at a time. We know

    # we reached the end when the next reference is None

    while current != None:

      count = count + 1

      current = current.get_next()

    return count

  '''

  Search for an item in the list. Returns True if found, False otherise.  

  '''

  def search(self,item):

    current = self.head

    found = False

    # As long as the element is not found and we haven't

    # reached the end of the list

    while current != None and not found:

      if current.get_data() == item:

        found = True

      else:

        # go to the next element

        current = current.get_next()

    return found

   

  '''

  Remove the first occurrence of item from the list.  

  '''

  def remove(self, item):

    # keep track of current and previous elements

    current = self.head

    previous = None

    found = False

    # traverse the list

    while current != None and not found:

      # if we have a match, stop

      if current.get_data() == item:

        found = True

      # otherwise advance current and next references

      else:

        previous = current

        current = current.get_next()

      

    # the element to be deleted is the head of the list   

    if found:

      if previous == None:

        self.head = current.get_next()

        # the element to be deleted is not the head

      else:

        previous.set_next(current.get_next())

      

      

def main():

  # create a list and add some elements to it

  aList = UnorderedList()

  print("Adding 3, 5, 8, and 11 to the list.")

  aList.add(3)

  aList.add(5)

  aList.add(8)

  # 11 is the head of the list

  aList.add(11)

   

  print("List size:", aList.size())

  print("Is 5 in the list? ", aList.search(5))

  print("Removing 5 from the list.")

  aList.remove(5)

  print("Is 5 in the list? ", aList.search(5))

  print("List size:", aList.size())

  print("Removing 3 from the list.")

  aList.remove(3)   

  print("List size:", aList.size())

  

if __name__ == "__main__":

  main()

Solutions

Expert Solution

Here is a python code with implementation of print_list() method :

from Node import Node

class UnorderedList:

  '''

  List is empty upon creation and the head reference is None

  '''

  def __init__(self):

    self.head = None   

     

  '''

  Returns True if list is empty, False otherwise

  '''

  def is_empty(self):

    return self.head == None

   

  '''

  Add an element to head of the list

  '''

  def add(self, item):

    # Create a node using item as its data

    temp = Node(item)

    # make the next reference of the new node refer to the head

    # of the list

    temp.set_next(self.head)

    # modify the list head so that it references the new node

    self.head = temp

     

  '''

  Returns the size of the list

  '''

  def size(self):

    # start at the head of the list

    current = self.head

    count = 0

    # Traverse the list one element at a time. We know

    # we reached the end when the next reference is None

    while current != None:

      count = count + 1

      current = current.get_next()

    return count

  '''

  Search for an item in the list. Returns True if found, False otherise.  

  '''

  def search(self,item):

    current = self.head

    found = False

    # As long as the element is not found and we haven't

    # reached the end of the list

    while current != None and not found:

      if current.get_data() == item:

        found = True

      else:

        # go to the next element

        current = current.get_next()

    return found

   

  '''

  Remove the first occurrence of item from the list.  

  '''

  def remove(self, item):

    # keep track of current and previous elements

    current = self.head

    previous = None

    found = False

    # traverse the list

    while current != None and not found:

      # if we have a match, stop

      if current.get_data() == item:

        found = True

      # otherwise advance current and next references

      else:

        previous = current

        current = current.get_next()

      

    # the element to be deleted is the head of the list   

    if found:

      if previous == None:

        self.head = current.get_next()

        # the element to be deleted is not the head

      else:

        previous.set_next(current.get_next())

              
  def print_list(self):
    current = self.head
    # start of list
    print('[',end="")
    while current != None:
      print(current.get_data(),end="")

      current = current.get_next()

      # to avoid printing comma after last element
      if(current!=None):
        print(', ',end="")

    print(']')


def main():

  # create a list and add some elements to it

  aList = UnorderedList()

  print("Adding 3, 5, 8, and 11 to the list.")

  aList.add(3)

  aList.add(5)

  aList.add(8)

  # 11 is the head of the list

  aList.add(11)

   

  print("List size:", aList.size())

  print("Is 5 in the list? ", aList.search(5))

  print("Removing 5 from the list.")

  aList.remove(5)

  print("Is 5 in the list? ", aList.search(5))

  print("List size:", aList.size())

  print("Removing 3 from the list.")

  aList.remove(3)   

  print("List size:", aList.size())

  aList.print_list()
  

if __name__ == "__main__":

  main()

Related Solutions

Given the LinkedStack Class as covered in class add a method to the LinkedStack class called...
Given the LinkedStack Class as covered in class add a method to the LinkedStack class called PushBottom which will add a new item to the bottom of the stack. The push bottom will increase the number of items in the stack by 1
In Java please: 1) Part 1: Edit the getTileList method (add length method too) Dear Developer,...
In Java please: 1) Part 1: Edit the getTileList method (add length method too) Dear Developer, It seems an overzealous programmer tried to create a Fibonacci slider puzzle from our old code. This brought up the fact there is a data integrity issue in our SlidingSquarePuzzle class. It makes sense because the class’s data only consists of an int[]. Since, you are new this is a good opportunity to get your feet wet. I want you to change the offending...
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the...
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the phone number that's incremented. Given Files: public class Demo4 { public static void main(String[] args) { SmartPhone test1 = new SmartPhone("Bret", "1234567890"); SmartPhone test2 = new SmartPhone("Alice", "8059226966", "[email protected]"); SmartPhone test3 = new SmartPhone(); SmartPhone test4 = new SmartPhone("Carlos", "8189998999", "[email protected]"); SmartPhone test5 = new SmartPhone("Dan", "8182293899", "[email protected]"); System.out.print(test1); System.out.println("Telephone neighbor: " + test1.getTeleponeNeighbor()); System.out.println(); System.out.print(test2); System.out.println("Telephone neighbor: " + test2.getTeleponeNeighbor()); System.out.println(); System.out.print(test3); System.out.println("Telephone...
Add the following method below to the CardDeck class, and create a test driver to show...
Add the following method below to the CardDeck class, and create a test driver to show that they work correctly. int cardsRemaining() //returns a count of the number of undealt cards remaining in the deck. Complete in Java programming language. // Models a deck of cards. Includes shuffling and dealing. //---------------------------------------------------------------------- package Homework4; import java.util.Random; import java.util.Iterator; import javax.swing.ImageIcon; public class CardDeck { public static final int NUMCARDS = 52; protected ABList<Card> deck; protected Iterator<Card> deal; public CardDeck() { deck...
Given the following definition of the LNode class, implement the non-recursive method saveCountinLastNode and the recursive...
Given the following definition of the LNode class, implement the non-recursive method saveCountinLastNode and the recursive method addOddNodes for the LinkedList class which represents singly linked lists. public class LNode { private int m_info; private LNode m_link; public LNode(int info){ m_info = info; m_link = null; } public void setLink(LNode link){ m_link = link; } public LNode getLink(){   return m_link; } public void setInfo(int info){ m_info = info; } public int getInfo(){   return m_info; } } public class LinkedList {...
What is the issue is in the add method in the SongList Class? It doesn't seem...
What is the issue is in the add method in the SongList Class? It doesn't seem to add the songs when running testing. public class Song { // instance variables private String m_artist; private String m_title; private Song m_link; // constructor public Song(String artist, String title) { m_artist = artist; m_title = title; m_link = null; } // getters and setters public void setArtist(String artist) { m_artist = artist; } public String getArtist() { return m_artist; } public void setTitle(String...
Java Language -Create a project and a class with a main method, TestCollectors. -Add new class,...
Java Language -Create a project and a class with a main method, TestCollectors. -Add new class, Collector, which has an int instance variable collected, to keep track of how many of something they collected, another available, for how many of that thing exist, and a boolean completist, which is true if we want to collect every item available, or false if we don't care about having the complete set. -Add a method addToCollection. In this method, add one to collected...
1. Please create a New Class with the Class Name: Class17Ex Please add the ten methods:...
1. Please create a New Class with the Class Name: Class17Ex Please add the ten methods: 1. numberOfStudents 2. getName 3. getStudentID 4. getCredits 5. getLoginName 6. getTime 7. getValue 8. getDisplayValue 9. sum 10. max Show Class17Ex.java file with full working please. Let me know if you have any questions.
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a BankAccountconstructed from data input from the keyboard. Override ReadAccount in SavingsAccount to return an account that refers to a SavingsAccount that you construct, again initializing it with data from the keyboard. Similarly, implement ReadAccount in the CheckingAccount class. Use the following code to test your work. public static void testCode()         {             SavingsAccount savings = new SavingsAccount(100.00, 3.5);             SavingsAccount s = (SavingsAccount)savings.ReadAccount();...
Add a method to OurQueue class that dequeues the Nth item on a queue and returns...
Add a method to OurQueue class that dequeues the Nth item on a queue and returns it. It must remove the Nth item from the Queue but leave the rest of the queue. Test it with the following code: Console.WriteLine("Testing DequeueNth"); OurQueue<string> ourQ = new OurQueue<string>(12); // Empty Q try { ourQ.DequeueNth(0); Console.WriteLine("\a Error on empty list"); } catch { Console.WriteLine("Empty Queue worked"); } for (int i = 0; i < 9; ++i) ourQ.Enqueue("a" + i); for (int i =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT