Question

In: Computer Science

​​​​​​This is an assignment that I'm having trouble figuring out in python: Modify Node class so...

​​​​​​This is an assignment that I'm having trouble figuring out in python:

  • Modify Node class so it has a field called frequency and initialize it as one.

  • Add a search function. If a number is in the list, return its frequency.

  • Modify Insert function. Remove push, append, and insertAfter as one function called insert(self, data). If you insert a data that is already in the list, simply increase this node’s frequency. If the number is not in the list, add it to the beginning of the list.

  • Modify Delete function. When you delete a node, reduce its frequency. If frequency becomes zero, remove the node from the list.

  • Modify Print function to print out all the numbers with their frequency in the list.

The program that we are suppose to modify:

class Node:
def __init__(self,d):
self.data=d;# data in the node
self.next=None #address of next node
"""add a field called frequency here"""
class LinkedList:
def __init__(self):
self.head=None #linked list at the beginning is empty. head is None
  
def print(self):#print every node's data
temp=self.head#let temp points to head
while temp:#As long as temp is not None (the end)
"""modify print, so frequency is also printed out frequency """
print(temp.data,end="")#print data
temp=temp.next # let temp points to the next Node
print()
"""complete the folloing function """   
def insert(self,d):
temp=self.head
"""
travel the list like print, if d is in there break the loop
if yes, increase its freq
if not add it the front of the list like "push"
"""
  
  

"""
def push(self,new_d):#will add new node at the beginning
newNode=Node(new_d) #create a Node
newNode.next=self.head #Let new Node's next to be the original head
self.head=newNode #update head as the New Node
def insertAfter(self,prev_data, new_data):
temp=self.head#let temp be the head
while temp and temp.data!=prev_data:#as long temp is not None and data is not prev_data
temp=temp.next
#if you can get here. One of the condition must be false
if temp==None:#There is no prev_data because you have reached the end
print("The given previous node does not exist")
return
#if you can reach here, temp.data=prev.data
newNode=Node(new_data)#create a new node after Node temp
  
newNode.next=temp.next#make newNode's next as temp's next
temp.next=newNode# make temp's(prev) next as NewNode
def append(self,new_data):# add new_data at the end of the list
newNode=Node(new_data)#create a Node with new_data

if self.head==None:#in case the list is empty
self.head=newNode
return

last=self.head#let last be head
while last.next:#as long last next is not None, continue
last=last.next# let last as its next
#when loop terminates, last.next is None, therefore last points to the last Node
last.next=newNode
"""
def delete(self,key):#delete a Node with data "key"
temp=self.head #let temp be head
if temp is not None:#if list is not empty
if temp.data==key:#if key is at the first Node
"""reduce temp'frequency
if its frequency becomes 0, execute the next three lines"""
self.head=temp.next #let head to head's next
temp=None
return
  
while temp is not None:#if list is not empty
if temp.data==key:#loop ends if key is found
break
prev=temp#prev is node before
temp=temp.next
#Loop ends either temp is None or loop ends because of "break" which means key is found
if temp==None:
return #return because key is not in the list
#when temp.data is same as key
"""reduce temp'frequency
if its frequency becomes 0, execute the next three lines"""
prev.next=temp.next
temp=None
  
  
  
  
  
list=LinkedList()
list.insert(5)
list.insert(9)
list.insert(5)
list.insert(6)
list.insert(6)
list.insert(9)

list.print()
list.delete(5)
list.print()
list.delete(5)
list.print()
list.delete(6)
list.print()
list.delete(6)
list.print()

  

Solutions

Expert Solution

Modified classNode.py file


class Node:
        def __init__(self,d):
                self.data=d;# data in the node
                self.next=None #address of next node
                self.frequency = 1      #frequency of data in the node

class LinkedList:
        def __init__(self):
                self.head=None #linked list at the beginning is empty. head is None
          
        def print(self):#print every node's data
                temp=self.head#let temp points to head
                while temp:#As long as temp is not None (the end)
                        print(f"({temp.data}, {temp.frequency})",end="->")#print data
                        temp=temp.next #let temp points to the next Node
                print(None)#printing None at the end
          
        def insert(self, data):#inserting new node if not present else increasing its frequency
                temp=self.head  #temp points to head node
                while temp:     #As long as temp is not None
                        if temp.data == data:   #break loop if temp node data is given data
                                break
                        temp = temp.next        #temp now points to next node
                if temp:        #if temp is a valid addr and not None
                        temp.frequency += 1     #increase temp node frequency
                else:   #else if node not present
                        temp = Node(data)       #initialise a new Node in temp
                        temp.next = self.head   #point temp.next to head
                        self.head = temp        #now make temp as head node

        def search(self, data): #searches for given data and returns frequency if not present returns 0
                temp = self.head        #initially temp points to head node
                while temp:     #As long as temp is not None
                        if temp.data == data:   #if temp.data matches with given data
                                return temp.frequency   #returning temp.frequency
                        temp = temp.next        #now temp points to next node
                return 0        #if data is not found returning 0 as frequency

        def delete(self, key):  #deletes given key from linkedlist if present reduces frequncy and if frequency becomes 0 deletes that node
                temp = self.head        #initially points to head node
                prev = None     #And previous node is None so declared as None initially
                while temp:     #As long as temp is not None
                        if temp.data == key:    #if temp data matches with given key break
                                break
                        prev = temp     #previous points to temp (current node)
                        temp = temp.next        #temp points to next node
                if temp:        #if temp is not None
                        temp.frequency -= 1     #reduce frequency
                        if temp.frequency == 0: #if frequency becomes 0
                                if temp == self.head:   #if temp is head node
                                        self.head = temp.next   #updating the head node as next node to temp 
                                else:   #else
                                        prev.next = temp.next   #updating next node to previous node as next node to temp
                                del temp #deleting temp node as frequency is 0

#sample test

list=LinkedList()
list.insert(5)
list.insert(9)
list.insert(5)
list.insert(6)
list.insert(6)
list.insert(9)

list.print()
list.delete(5)
list.print()
list.delete(5)
list.print()
list.delete(6)
list.print()
list.delete(6)
list.print()

Screenshot of modified classNode.py file

Output Screenshot

Each and everything is explained clearly in the comment section of the code.

Thank you! Hit like if you like my work.


Related Solutions

I'm having trouble figuring out the constraints to this problem. I know that I am maximizing...
I'm having trouble figuring out the constraints to this problem. I know that I am maximizing 55x + 45y, however the variables are throwing me off. I only need help on question #1 as it would be a great help to understanding the rest of what the questions are asking. The problem is as follows: NorCal Outfitters manufactures a variety of specialty gear for outdoor enthusiasts. NorCal has decided to begin production on two new models of crampons: the Denali...
Hey! I'm having trouble answering this for my assignment. Thank you so much in advance. 1)...
Hey! I'm having trouble answering this for my assignment. Thank you so much in advance. 1) Which type of vessels, arteries or veins, has more muscle fibers? What is the functional significance of this? 2a) In general, we have no conscious control over smooth muscle or cardiac muscle function, whereas we can consciously control to some extent all skeletal muscles. Can you consciously control your breathing? What does this tell you about the muscle type of the diaphragm? 2b) What...
I have figured out this assignment, but I am having a hard time figuring out the...
I have figured out this assignment, but I am having a hard time figuring out the extra credit, Thanks! Creating a Rectangle class We have created a representation of a rectangle in C++ and extended it to create multiple representation's of rectangles. Classes can simplify that process considerably. In this assignment, your task is to convert the representation of a rectangle we created earlier in the semester to a Rectangle class. The Rectangle class shall consist of the following: The...
Can you balance these redox equations? I am having trouble figuring out the process of adding...
Can you balance these redox equations? I am having trouble figuring out the process of adding extra products to make them work. ClO3- + Cl- -----> Cl2 + ClO2- Cr2O72- + C2O42- -----> Cr3+ + CO2
I'm having trouble with these few questions out of a long list of journal entries that...
I'm having trouble with these few questions out of a long list of journal entries that I have to record for a project. If you could please state the journal entries for these and why that would be very helpful. Thank you! May 2 – Sold merchandise on credit to Yellow Rock Company, Invoice No. 9501, for $4,500 (cost is $2,000). I get the first part of the journal entry but don't know how to record the cost. May 3...
[PYTHON] Modify the examaverages.py program included with this assignment so it will also compute the overall...
[PYTHON] Modify the examaverages.py program included with this assignment so it will also compute the overall average test grade. E.g if there are 3 test each student must take and the user enters the following set of test scores for the two students…: 30, 40, 50 for the first student 50, 60, 70 for the second student …then program will print the average for each student (i.e. 40 for the first student and 60 for the second student – the...
I'm having trouble understanding a CS assignment. I would appreciate it if you all code do...
I'm having trouble understanding a CS assignment. I would appreciate it if you all code do this for me. The template for the lab is below which you must use. You're only supposed to create/edit the product function. The assignment has to be written in asm(Mips) You will need to create a NOS table and use the structure below and write a function called product. The structure used in this program is: struct Values { short left; short right; int...
I'm having trouble with my do while loop. I'm trying to get it where if the...
I'm having trouble with my do while loop. I'm trying to get it where if the user enter's 3 after whatever amount of caffeinated beverages they've entered before then the loop will close and the rest of my code would proceed to execute and calculate the average price of all the caffeinated beverages entered. Can someone please help me with this? Here's my Code: import java.util.Scanner; public class Main { public static void main(String[] args) { CaffeinatedBeverage[] inventory = new...
I am having difficulties with figuring out the formulas for this this question. Is there a...
I am having difficulties with figuring out the formulas for this this question. Is there a walk-through for this? You are the manager of a monopoly that sells a product to two groups of consumers in different parts of the country. Group 1’s elasticity of demand is -2, while group 2’s is -3. Your marginal cost of producing the product is $30. a. You are a monopolist. b. You compete against one other firm in a Cournot oligopoly. c. You...
I'm having trouble creating a histogram using openCV (color segmentation)
I'm having trouble creating a histogram using openCV (color segmentation)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT