Question

In: Computer Science

The following SinglyLinkedList class is available: class SinglyLinkedList: class _Node: """Lightweight, nonpublic class for storing a...

The following SinglyLinkedList class is available:

class SinglyLinkedList:
    class _Node:
        """Lightweight, nonpublic class for storing a singly linked node."""
        __slots__ = 'element', 'next'       # streamline memory usage

        def __init__(self, element, next):  # initialize node's fields
            self.element = element          # reference to user's element
            self.next = next                # reference to next node

    def __init__(self):          # initialize list's fields
        self._head = None        # head references to None

    def printList(self, label):
        print(label, end=' ')
        curr = self._head
        while curr != None:
            print(curr.element, end=" -> ")
            curr = curr.next
        print("/")

    #########################################################
    # Only this method is required for your solution
    def computeStats(self):
        # Your code goes here

    #########################################################

def main():
    # Create a list object for testing purpose
    sList = SinglyLinkedList()

    # Create list 2 -> 4 -> -1 -> 8 -> -5
    sList._head = sList._Node(2, sList._Node(4, sList._Node(-1, sList._Node(8, sList._Node(-5, None)))))
    sList.printList("before:")

    # Call computeStats method
    sList.computeStats()

    # And see if it worked!
    sList.printList("after :")

if __name__=="__main__":
    main()

Assume you have a singly-linked list of integers, some positive and some negative. Write a Python method that traverses this list to calculate both the average and the count (ie, number) of the odd values only. Once calculated, add the average to a new node at the front of the list, and the count to a new node at the end of the list. You may assume that the list will always contain at least one odd value.

Your method will be have the following method signature:

def computeStats(self):

You may use only the SinglyLinkedList class; no other methods (like size(), etc) are available.

For example, if the list initially contains:

2 → 4 → -1 → 8 → -5

the resulting list will contain:

-3.0 → 2 → 4 → -1 → 8 → -5 → 2

Solutions

Expert Solution



class SinglyLinkedList:
    class _Node:
        """Lightweight, nonpublic class for storing a singly linked node."""
        __slots__ = 'element', 'next'       # streamline memory usage

        def __init__(self, element, next):  # initialize node's fields
            self.element = element          # reference to user's element
            self.next = next                # reference to next node

    def __init__(self):          # initialize list's fields
        self._head = None        # head references to None

    def printList(self, label):
        print(label, end=' ')
        curr = self._head
        while curr != None:
            print(curr.element, end=" -> ")
            curr = curr.next
        print("/")

    #########################################################
    # Only this method is required for your solution
    def computeStats(self):
        # Your code goes here
        sum = 0
        count = 0
        curr = self._head
        pre = None
        while curr != None:
            if curr.element % 2 == 1:
                count += 1
                sum += curr.element
            pre = curr
            curr = curr.next
        pre.next = self._Node(count, None)
        newnode = self._Node(sum/count, self._head)
        self._head = newnode
    #########################################################

def main():
    # Create a list object for testing purpose
    sList = SinglyLinkedList()

    # Create list 2 -> 4 -> -1 -> 8 -> -5
    sList._head = sList._Node(2, sList._Node(4, sList._Node(-1, sList._Node(8, sList._Node(-5, None)))))
    sList.printList("before:")

    # Call computeStats method
    sList.computeStats()

    # And see if it worked!
    sList.printList("after :")

if __name__=="__main__":
    main()


Output

before: 2 -> 4 -> -1 -> 8 -> -5 -> /
after : -3.0 -> 2 -> 4 -> -1 -> 8 -> -5 -> 2 -> /

Solving your question and helping you to well understand it is my focus. So if you face any difficulties regarding this please let me know through the comments. I will try my best to assist you. However if you are satisfied with the answer please don't forget to give your feedback. Your feedback is very precious to us, so don't give negative feedback without showing proper reason.

Thank you.


Related Solutions

//LinkNode is a class for storing a single node of a linked list storing integer values....
//LinkNode is a class for storing a single node of a linked list storing integer values. It has two public data fields for the data and the link to //the next node in the list and has three constructors: public class LinkNode { public int data;       public LinkNode next; // post: constructs a node with data 0 and null link public ListNode() {      this(0, null); } // post: constructs a node with given data and null link public LinkNode (int...
This is a JAVA assignment and i dont have the SinglyLinkedList class   Exercise 1 In this...
This is a JAVA assignment and i dont have the SinglyLinkedList class   Exercise 1 In this exercise, you will add a method swapNodes to SinglyLinkedList class. This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. Hint: You may need to traverse the list. Exercise 2...
Please Use C++ to finish as the requirements. Implement a class called SinglyLinkedList. In the main...
Please Use C++ to finish as the requirements. Implement a class called SinglyLinkedList. In the main function, instantiate the SinglyLinkedList class. Your program should provide a user loop and a menu so that the user can access all the operators provided by the SinglyLinkedList class. DestroyList InitializeList GetFirst InsertFirst, InsertLast, Insert DeleteFirst, DeleteLast, Delete IsEmpty Length Print, ReversePrint
in java: Write a class responsible for storing data in a text file. The class should...
in java: Write a class responsible for storing data in a text file. The class should include a method that accepts a string and appends it to a file.
How to combine these 2 main functions of c++ files in 1 main class? //SinglyLinkedList int...
How to combine these 2 main functions of c++ files in 1 main class? //SinglyLinkedList int main() { SinglyLinkedList<std::string> list; list.Add("Hello"); list.Print(); list.Add("Hi"); list.Print(); list.InsertAt("Bye",1); list.Print(); list.Add("Akash"); list.Print(); if(list.isEmpty()){ cout<<"List is Empty "<<endl; } else{ cout<<"List is not empty"<<endl; } cout<<"Size = "<<list.Size()<<endl; cout<<"Element at position 1 is "<<list.get(1)<<endl; if(list.Contains("X")){ cout<<"List contains X"<<endl; } else{ cout<<"List does not contain X"<<endl; } cout<<"Position of the word Akash is "<<list.IndexOf("Akash")<<endl; cout<<"Last Position of the word Akash is "<<list.LastOf("Akash")<<endl; list.RemoveElement("Akash"); cout<<"After removing Akash...
C++ Define a class PersonalRecord, which will be storing an employee’s information. Internally, the class should...
C++ Define a class PersonalRecord, which will be storing an employee’s information. Internally, the class should have the following attributes: SSN (string type), fullName (string type), homeAddress (string type), phoneNumber (string type), salaryRate (per year, float type), and vacationDays (accrued vacation, int type). The constructor should take six parameters: four of them are necessary to provide values to at the time of initialization (when a constructor will be called/invoked): SSN, fullName, homeAddress, and phoneNumber; and two of them are optional...
For a physiology class experiment, a student is fitted with a lightweight waterproof device that measures...
For a physiology class experiment, a student is fitted with a lightweight waterproof device that measures her average pulse rate over 2-hourly intervals. Consider 12 consecutive intervals over a 24-hour period, and let X be the number of these intervals in which the average pulse rate is less than 100 beats per minute. Is it reasonable to treat X as an observation from a binomial distribution? Justify your answer.
HashMap is a Map based collection class that is used for storing Key & value pairs,...
HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. This class makes no guarantees as to the order of the map. It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key). 5.Write a Java program to test if a map contains a mapping for the specified key.a.Add values in the Hash mapb.Printthe mapc.Check for a...
Answers will be given extra reward Convert the following SINGLYLINKEDLIST code into DOUBLYLINKEDLIST code. Such that...
Answers will be given extra reward Convert the following SINGLYLINKEDLIST code into DOUBLYLINKEDLIST code. Such that struct Node { int element; structNode*next; structNode*prev; } struct Node *head = NULL; structNode*tail =NULL; The SINGLYLINKEDLIST code is as follows: #include <stdio.h> #include <stdlib.h> struct Node{ int element; struct Node *next; }; void get(struct Node *head, int pos) { struct Node *temp; temp = head;    if(head == NULL) { printf("List is empty!\n"); }    for(int i=0; i < pos; i++) temp =...
1. Which of the following is not a required paragraph in unmodified paragraph for US nonpublic...
1. Which of the following is not a required paragraph in unmodified paragraph for US nonpublic companies? Introductory Paragraph Auditor’s responsibilities paragraph Management’s responsibilities paragraph Signature, tenure, location, and date 2. When a subsequent event provides evidence about conditions that did not exist at the balance sheet date, the auditor should do which of the following? ensure that any necessary footnote disclosures be included with the statements. ensure that the financial statements are adjusted to reflect the information, including any...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT