Question

In: Computer Science

There are two calsses: node.py and a5.py. The a5.py contains three important methods: Length -> Outputs...

There are two calsses: node.py and a5.py. The a5.py contains three important methods:

  • Length -> Outputs the length of the linked list
  • Insert -> Inserts an element into the linked list
  • PrintStructure -> Prints the entire linked list starting from the head

The task is to fill in these methods given in the a5.py. Hints are given to you inside the a5.py class so make sure to check them out. Note that one of the important concepts in this example is that when a new element is inserted into the list, it gets inserted into it’s appropriate (sorted) position. Please take a look at the examples to see how random values are inputted and the result is sorted.

Please enter a word (or just hit enter to end): bottle

Please enter a word (or just hit enter to end): a

Please enter a word (or just hit enter to end): water Please enter a word (or just hit enter to end): of Please enter a word (or just hit enter to end):

The structure contains 4 items: a bottle of water

Please enter a word (or just hit enter to end): Ana

Please enter a word (or just hit enter to end): Bill

Please enter a word (or just hit enter to end): car

Please enter a word (or just hit enter to end): algorithm Please enter a word (or just hit enter to end): button Please enter a word (or just hit enter to end):

The structure contains 5 items: algorithm Ana Bill button car

NODE.PY

"""File: node.py

Node classes for one-way linked structures and two-way

linked structures."""

class Node(object):

def __init__(self, data, next = None):

"""Instantiates a Node with default next of None"""

self.data = data

self.next = next

A5.PY

"""
File: a5.py


Define a length function.
Define a printStructure function.
Define an insert function.
Test the above functions and the Node class.
"""

from node import Node

def length(head):
    """Returns the number of items in the linked structure
    referred to by head."""
    probe = head
    count = 0
   
    # ADD CODE HERE: Count the number of nodes in the structure
   
    return count
   
def insert(newItem, head):
    """Inserts newItem at the correct position (ascending order) in
    the linked structure referred to by head.
    Returns a reference to the new structure."""
    # if head == None:
        # if structure is empty
        # ADD CODE HERE       
    # else:
        #Insert newItem in its place (ascending order)
      # ADD CODE HERE
       
    return head

def printStructure(head):
    """Prints the items in the structure referred to by head."""
    # ADD CODE HERE

def main():
    """Gets words from the user and inserts in the
    structure referred to by head."""
   
    head = None
    userInput = input('Please enter a word (or just hit enter to end): ')
    while userInput != '':
        head = insert(userInput, head)
        userInput = input('Please enter a word (or just hit enter to end): ')
    print('The structure contains', length(head), 'items:')
    printStructure(head)

if __name__ == "__main__": main()

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

from Node import Node


def length(head):
    """Returns the number of items in the linked structure
    referred to by head."""
    probe = head
    count = 0
    #loops until probe is None
    while probe!=None:
        #updating count, advancing probe
        count+=1
        probe=probe.next
    return count


def insert(newItem, head):
    """Inserts newItem at the correct position (ascending order) in
    the linked structure referred to by head.
    Returns a reference to the new structure."""
    #creating a new node with newItem as data
    node=Node(newItem)
    #if head is None, returning node
    if head == None:
        return node
    #checking if newItem can be added before current head
    #assuming data is of string type, comparing without case sensitivity as
    #displayed by second example in the sample output (algorithm Ana Bill button car)
    if newItem.lower()<head.data.lower():
        #adding head as next of node and returning node
        node.next=head
        return node
    #taking a reference to head
    probe=head
    #loops until probe.next is None
    while probe.next!=None:
        #checking if element can be added between probe and probe.next
        if newItem.lower()>=probe.data.lower() and newItem.lower()<=probe.next.data.lower():
            #adding between the nodes and returning head
            node.next=probe.next
            probe.next=node
            return head
        probe=probe.next
    #if still not added, adding at last and returning head
    probe.next=node
    return head

    return head


def printStructure(head):
    """Prints the items in the structure referred to by head."""
    probe=head
    #looping and printing each item separated by white spaces
    while probe!=None:
        print(probe.data,end=' ')
        probe=probe.next
    print()


def main():
    """Gets words from the user and inserts in the
    structure referred to by head."""

    head = None
    userInput = input('Please enter a word (or just hit enter to end): ')
    while userInput != '':
        head = insert(userInput, head)
        userInput = input('Please enter a word (or just hit enter to end): ')
    print('The structure contains', length(head), 'items:')
    printStructure(head)


if __name__ == "__main__": main()

Related Solutions

Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are...
Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. Complete the ShoppingListArrayListTest.java (For many tests, we now just throw a false statement which will cause the test cases to fail. You need to complete them.) ShoppingListArrayList package Shopping; import DataStructures.*; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; /** * @version Spring 2019 * @author Paul Franklin, Kyle Kiefer */ public class ShoppingListArrayList implements ShoppingListADT { private ArrayList<Grocery> shoppingList;...
Box I contains three blue and two red marbles, Box II contains three blue and three...
Box I contains three blue and two red marbles, Box II contains three blue and three red marbles. Suppose one marble is drawn from Box I and placed in Box II and then one marble is drawn from Box II. Find the conditional probability that the marble drawn from Box I is blue given that the marble drawn from Box II is red.
a C++ program that reads in weight in pounds and outputs the equivalent length in Kilograms...
a C++ program that reads in weight in pounds and outputs the equivalent length in Kilograms and grams. Use at least three functions: one for input, one or more for calculating, and one for output. Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program. 1 pound (lb) is equal to 0.45359237 kilograms (kg). There are 1000 grams in a kilogram and 16 ounces...
a C++ program that reads in weight in pounds and outputs the equivalent length in Kilograms...
a C++ program that reads in weight in pounds and outputs the equivalent length in Kilograms and grams. Use at least three functions: one for input, one or more for calculating, and one for output. Include a loop that lets the user repeat this computation for new input values until the user says he or she wants to end the program. 1 pound (lb) is equal to 0.45359237 kilograms (kg). There are 1000 grams in a kilogram, and 16 ounces...
In a thought experiment, a cubic box of side length 0.01 mm contains three particles. One...
In a thought experiment, a cubic box of side length 0.01 mm contains three particles. One particle moves just in the x-direction, colliding elastically with the left and right walls of the cube. The second atom moves just in the y-direction, colliding elastically with the front and back walls of the cube. The third atom moves just in the z-direction, colliding elastically with the top and bottom walls of the cube. All three atoms have speed 500 m/s and mass...
What is exception propagation? Give an example of a class that contains at least two methods,...
What is exception propagation? Give an example of a class that contains at least two methods, in which one method calls another. Ensure that the subordinate method will call a predefined Java method that can throw a checked exception. The subordinate method should not catch the exception. Explain how exception propagation will occur in your example.
What are the outputs of the accounting cycle? Why are they important? Identify and explain the...
What are the outputs of the accounting cycle? Why are they important? Identify and explain the purpose of each financial statement, including how they are interrelated.
Write C code that contains a function called triangle_generator that outputs a triangle wave at a...
Write C code that contains a function called triangle_generator that outputs a triangle wave at a specified frequency (in hertz) using a specified sample rate (in hertz), and for a specified time duration (in seconds). These parameters are float type. The output you generate are floating point numbers between -1 and 1, one number per output line. The math trig functions in C use radians while all the specifications here are in hertz (cycles per second). One hertz is 2*Pi...
Write a simple java class that contains the following three methods: 1. isosceles -- accepts 3...
Write a simple java class that contains the following three methods: 1. isosceles -- accepts 3 integers which represent the sides of a triangle. Returns true if the triangle is isosceles and false otherwise. 2. perimeter - accepts 3 integers that represent the sides of a triangle and returns the perimeter of the triangle. 3. area -- accepts 3 integers, which represent the sides of a triangle and calculates and returns the area of the triangle. Hint: use Heron's formula....
Write a Calculate class which contains methods that accepts two integers as arguments and return the...
Write a Calculate class which contains methods that accepts two integers as arguments and return the results of Addition, Subtraction, Division and Multiplication. Call these methods though main()and print the results.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT