
Concept explainers
class SLNode:
"""
Singly Linked List Node class
DO NOT CHANGE THIS CLASS IN ANY WAY
"""
def __init__(self, value: object, next=None) -> None:
self.value = value
self.next = next
from SLNode import *
class SLLException(Exception):
"""
Custom exception class to be used by Singly Linked List
DO NOT CHANGE THIS CLASS IN ANY WAY
"""
pass
class LinkedList:
def __init__(self, start_list=None) -> None:
"""
Initialize new linked list
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self._head = SLNode(None)
# populate SLL with initial values (if provided)
# before using this feature, implement insert_back() method
if start_list is not None:
for value in start_list:
self.insert_back(value)
def __str__(self) -> str:
"""
Return content of singly linked list in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
out = 'SLL ['
node = self._head.next
while node:
out += str(node.value)
if node.next:
out += ' -> '
node = node.next
out += ']'
return out
def length(self) -> int:
"""
Return the length of the linked list
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
length = 0
node = self._head.next
while node:
length += 1
node = node.next
return length
def is_empty(self) -> bool:
"""
Return True is list is empty, False otherwise
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
return not self._head.next
def insert_at_index(self, index: int, value: object) -> None:
"""
this implementation
"""
pass
![insert_at_index(self, index: int, value: object) -> None:
This method inserts a new value at the specified index position in the linked list. Index 0
refers to the beginning of the list (right after the front sentinel).
If the provided index is invalid, the method raises a custom "SLLException". Code for the
exception is provided in the skeleton file. If the linked list contains N nodes (the sentinel
node is not included in this count), valid indices for this method are [0, N] inclusive.
Example #1:
1st LinkedList ()
test cases
[(0, "A"), (0, "B"), (1, "C"), (3, "D"), (-1, "E"), (5, "F")]
for index, value in test_cases:
print("Inserted", value, "at index", index, ": ", end-"")
try:
1st.insert_at_index (index, value)
print (1st)
except Exception as e:
print (type (e))
Output:
Inserted A at index 0: SLL [A]
Inserted B at index
Inserted C at
index 1:
SLL [B -> C -> A)
Inserted D at index 3: SLL [B -> C -> A -> D]
Inserted E at index -1 : <class ' main
Inserted F at index 5: <class main
0: SLL [B -> A)
SLLException'>
.SLLException'>](https://content.bartleby.com/qna-images/question/96eb680b-bf96-4b4b-a2da-be1777b93ea0/bc544ec5-f53b-48be-8dc7-a25558b74771/52apjsp_thumbnail.png)

Trending nowThis is a popular solution!
Step by stepSolved in 3 steps

Please show the output
Please show the output
- Do not add import statementsarrow_forwarddef test_corr_coef(): list1 = [78.9, 75.8, 77.3, 74.2, 78.1, 72.8, 77.6, 77.9] list2 = [56.7, 53.1, 56.1, 55.9, 54.1, 48.6, 59.4, 54.0] assert round(corr_coef(list1, list2), 2) == 0.64 return test_corr_coef# Unit testprint (test_corr_coef) I added the print function and get this return please help.arrow_forwardC++ Program This assignment consists of 2 parts. 1. Append Process: Create a Linked List that will store integers. Using the provided getData() method (See below), append 20 numbers to the Linked List. After loaded, display the data. Start with the Head of the list. Prompt for user to proceed. 2. Insert Process: Delete the contents of the Linked List in part 1. Using the provided getData() method, insert 20 numbers into the list and place them in the list in numerical order (1..X). Do not allow duplicates to be in the list. Hint: Do not allow a duplicate to count as a member of the 20. After loaded, display the data per line in order, starting with the Head of the list. Display the content with a leading increasing number 1- 20. i.e. 11 13 14 20 The result should be a naturally sorted. Do not use the STL list container for this exercise. Use the features described in section - Linked List Operations. Using a Class to manage the linked list as shown in section is…arrow_forward
- program - python Question: Create a class called Candy which keeps track of the three pieces of information Read in the file line by line and create a Candy class instance for each candy bar you have, and add that new instance to a list. Once you have the list created, loop through the list and print the candy bar info out to the consoleUse this as an example: class Coord: def __init__(self, x, y): self.x = x self.y = y def main(): # creating list list = [] with open('C:\\Users\\owner\\Documents\\mycoords.txt') as f: for line in f: # print(line.strip()) words = line.split(',') x=float(words[0]) y=float(words[1]) list.append(Coord(x,y)) f.close() # Accessing object value using a for loop for p in list: print(f"Coordinate: x={p.x}, y={p.y}") print("") main()arrow_forwardException in thread "main" java.lang.NumberFormatException: For input string: "x" for Java code public class Finder { //Write two recursive functions, both of which will parse any length string that consists of digits and numbers. Both functions //should be in the same class and have the following signatures. //use the if/else statement , Find the base case and -1 till you get to base case //recursive function that adds up the digits in the String publicstaticint sumIt(String s) { //if String length is less or equal to 1 retrun 1. if (s.length()<= 1){ return Integer.parseInt(s); }else{ //use Integer.praseInt(s) to convert string to Integer //returns the interger values //else if the CharAt(value in index at 0 = 1) is not equal to the last vaule in the string else {//return the numeric values of a char value + call the SumIt method with a substring = 1 return Character.getNumericValue(s.charAt(0) ) + sumIt(s.substring(1)); } } //write a recursion function that will find…arrow_forward* QueueArrayList.java This file implements QueueInterface.java This file has * only one ArrayList<T> type of attribute to hold queue elements. One default * constructor initializes the ArrayList<T> queue. An enqueue method receives an * object and place the object into the queue. The enqueue method does not throw * overflow exception. A dequeue method returns and removes an object from queue * front. The dequeue method will throw exception with message "Underflow" when * the queue is empty. A size method returns number of elements in the queue. A * toString method returns a String showing size and all elements in the queue. Please help me in javaarrow_forward
- def analyze_file (filename: str, pos_words: List [str], neg_words: List [str]) -> Given the name of a file, a list of positive words (all in lowercase), and a list of negative words (all in lowercase), return some interesting data about the file in a tuple, with the first item in the tuple being the positivity score of the contents of this file, and the rest of the item: being whatever else you end up analyzing. (Helper functions are highly encouraged here.) How to calculate positivity score: For every word that is pos itive in the file (based on the words in the list of positive words) add 1 to the score. For every negative word (based on the list of negative words), subtract 1 from the score. Any neutral words (those that do not appear in either list) do not affect the score in any way. passarrow_forwardAssign negativeCntr with the number of negative values in the linked list. Thanks. // ===== Code from file IntNode.java =====public class IntNode {private int dataVal;private IntNode nextNodePtr; public IntNode(int dataInit, IntNode nextLoc) {this.dataVal = dataInit;this.nextNodePtr = nextLoc;} public IntNode(int dataInit) {this.dataVal = dataInit;this.nextNodePtr = null;} /* Insert node after this node.* Before: this -- next* After: this -- node -- next*/public void insertAfter(IntNode nodePtr) {IntNode tmpNext; tmpNext = this.nextNodePtr; // Remember nextthis.nextNodePtr = nodePtr; // this -- node -- ?nodePtr.nextNodePtr = tmpNext; // this -- node -- next} // Grab location pointed by nextNodePtrpublic IntNode getNext() {return this.nextNodePtr;}public int getDataVal() {return this.dataVal;}}// ===== end ===== // ===== Code from file CustomLinkedList.java =====import java.util.Random; public class CustomLinkedList {public static void main(String[] args) {Random randGen = new…arrow_forwardDesign a class that acquires the JSON string from question #1 and converts it to a class data member dictionary. Your class produces data sorted by key or value but not both. Provide searching by key capabilities to your class. Provide string functionality to convert the dictionary back into a JSON string. question #1: import requestsfrom bs4 import BeautifulSoupimport json class WebScraping: def __init__(self,url): self.url = url self.response = requests.get(self.url) self.soup = BeautifulSoup(self.response.text, 'html.parser') def extract_data(self): data = [] lines = self.response.text.splitlines()[57:] # Skip the first 57 lines for line in lines: if line.startswith('#'): # Skip comment lines continue values = line.split() row = { 'year': int(values[0]), 'month': int(values[1]), 'decimal_date': float(values[2]),…arrow_forward
- TRUE OR FALSE We can use Generics to define a custom generic exception.arrow_forwardCreate the Singly Linked List after having executed the following methods. Each item must have a headand tailreference. Whenever a method is not expected or invalid, write Exception. Only the process not the code •addHead("Dancing") •addHead("Backup") •addHead("Backup") •addTail("Backup") •addTail("Backup") •removeHead()arrow_forwardCreate class Test in a file named Test.java. This class contains a main program that performs the following actions: Instantiate a doubly linked list. Insert strings “a”, “b”, and “c” at the head of the list using three Insert() operations. The state of the list is now [“c”, “b”, “a”]. Set the current element to the second-to-last element with a call to Tail() followed by a call to Previous()Then insert string “d”. The state of the list is now [“c”, “d”, “b”, “a”]. Set the current element to past-the-end with a call to Tail() followed by a call to Next(). Then insert string “e”. The state of the list is now [“c”, “d”, “b”, “a”, “e”] . Print the list with a call to Print() and verify that the state of the list is correct.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education





