linear_classifier
.py
keyboard_arrow_up
School
University of Michigan *
*We aren’t endorsed by this school
Course
599
Subject
Computer Science
Date
Apr 3, 2024
Type
py
Pages
11
Uploaded by abigailrafter
"""
Implements linear classifeirs in PyTorch.
WARNING: you SHOULD NOT use ".to()" or ".cuda()" in each implementation block.
"""
import torch
import random
import statistics
from abc import abstractmethod
from typing import Dict, List, Callable, Optional
def hello_linear_classifier():
"""
This is a sample function that we will try to import and run to ensure that
our environment is correctly set up on Google Colab.
"""
print("Hello from linear_classifier.py!")
# Template class modules that we will use later: Do not edit/modify this class
class LinearClassifier:
"""An abstarct class for the linear classifiers"""
# Note: We will re-use `LinearClassifier' in both SVM and Softmax
def __init__(self):
random.seed(0)
torch.manual_seed(0)
self.W = None
def train(
self,
X_train: torch.Tensor,
y_train: torch.Tensor,
learning_rate: float = 1e-3,
reg: float = 1e-5,
num_iters: int = 100,
batch_size: int = 200,
verbose: bool = False,
):
train_args = (
self.loss,
self.W,
X_train,
y_train,
learning_rate,
reg,
num_iters,
batch_size,
verbose,
)
self.W, loss_history = train_linear_classifier(*train_args)
return loss_history
def predict(self, X: torch.Tensor):
return predict_linear_classifier(self.W, X)
@abstractmethod
def loss(
self,
W: torch.Tensor,
X_batch: torch.Tensor,
y_batch: torch.Tensor,
reg: float,
):
"""
Compute the loss function and its derivative.
Subclasses will override this.
Inputs:
- W: A PyTorch tensor of shape (D, C) containing (trained) weight of a model.
- X_batch: A PyTorch tensor of shape (N, D) containing a minibatch of N
data points; each point has dimension D.
- y_batch: A PyTorch tensor of shape (N,) containing labels for the minibatch.
- reg: (float) regularization strength.
Returns: A tuple containing:
- loss as a single float
- gradient with respect to self.W; an tensor of the same shape as W
"""
raise NotImplementedError
def _loss(self, X_batch: torch.Tensor, y_batch: torch.Tensor, reg: float):
self.loss(self.W, X_batch, y_batch, reg)
def save(self, path: str):
torch.save({"W": self.W}, path)
print("Saved in {}".format(path))
def load(self, path: str):
W_dict = torch.load(path, map_location="cpu")
self.W = W_dict["W"]
if self.W is None:
raise Exception("Failed to load your checkpoint")
# print("load checkpoint file: {}".format(path))
class LinearSVM(LinearClassifier):
"""A subclass that uses the Multiclass SVM loss function"""
def loss(
self,
W: torch.Tensor,
X_batch: torch.Tensor,
y_batch: torch.Tensor,
reg: float,
):
return svm_loss_vectorized(W, X_batch, y_batch, reg)
class Softmax(LinearClassifier):
"""A subclass that uses the Softmax + Cross-entropy loss function"""
def loss(
self,
W: torch.Tensor,
X_batch: torch.Tensor,
y_batch: torch.Tensor,
reg: float,
):
return softmax_loss_vectorized(W, X_batch, y_batch, reg)
# **************************************************#
################## Section 1: SVM ##################
# **************************************************#
def svm_loss_naive(
W: torch.Tensor, X: torch.Tensor, y: torch.Tensor, reg: float
):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples. When you implment the regularization over W, please DO NOT
multiply the regularization term by 1/2 (no coefficient).
Inputs:
- W: A PyTorch tensor of shape (D, C) containing weights.
- X: A PyTorch tensor of shape (N, D) containing a minibatch of data.
- y: A PyTorch tensor of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as torch scalar
- gradient of loss with respect to weights W; a tensor of same shape as W
"""
dW = torch.zeros_like(W) # initialize the gradient as zero
# compute the loss and the gradient
num_classes = W.shape[1]
num_train = X.shape[0]
loss = 0.0
for i in range(num_train):
scores = W.t().mv(X[i])
correct_class_score = scores[y[i]]
for j in range(num_classes):
if j == y[i]:
continue
margin = scores[j] - correct_class_score + 1 # note delta = 1
if margin > 0:
loss += margin
#######################################################################
# TODO: #
# Compute the gradient of the SVM term of the loss function and store #
# it on dW. (part 1) Rather than first computing the loss and then #
# computing the derivative, it is simple to compute the derivative #
# at the same time that the loss is being computed. #
#######################################################################
# Replace "pass" statement with your code
dW[:,y[i]] -= X[i]/num_train
dW[:,j] += X[i]/num_train
#######################################################################
# END OF YOUR CODE #
#######################################################################
# Right now the loss is a sum over all training examples, but we want it
# to be an average instead so we divide by num_train.
loss = loss/num_train
# Add regularization to the loss.
loss += reg * torch.sum(W * W)
#############################################################################
# TODO: #
# Compute the gradient of the loss function w.r.t. the regularization term #
# and add it to dW. (part 2) #
#############################################################################
# Replace "pass" statement with your code
dW += 2*reg*W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
def svm_loss_vectorized(
W: torch.Tensor, X: torch.Tensor, y: torch.Tensor, reg: float
):
"""
Structured SVM loss function, vectorized implementation. When you implment
the regularization over W, please DO NOT multiply the regularization term by
1/2 (no coefficient). The inputs and outputs are the same as svm_loss_naive.
Inputs:
- W: A PyTorch tensor of shape (D, C) containing weights.
- X: A PyTorch tensor of shape (N, D) containing a minibatch of data.
- y: A PyTorch tensor of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as torch scalar
- gradient of loss with respect to weights W; a tensor of same shape as W
"""
loss = 0.0
dW = torch.zeros_like(W) # initialize the gradient as zero
num_classes = W.shape[1]
num_train = X.shape[0]
#############################################################################
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
Need help making a java file that combines both linearSearch and binarySearch
•Both search methods must use the Comparable<T> interface and the compareTo() method.•Your program must be able to handle different data types, i.e., use generics.•For binarySearch, if you decide to use a midpoint computation formula that is different fromthe textbook, explain that formula briefly as a comment within your code.
//code from textbook
//linearSearch
public static <T> boolean linearSearch(T[] data, int min, int max, T target) { int index = min; boolean found = false; while (!found && index <= max) { found = data [index].equals(target); index++; } return found; }
//binarySearch
public static <T extends Comparable<T>> boolean binarySearch(T[] data, int min, int max, T target) { boolean found = false; int midpoint = (min + max)/2; if (data[midpoint].compareTo(target)==0)…
arrow_forward
Help with c++... please paste indented code plzz and keep output same as given
arrow_forward
Can you help with with the following questions, regarding population genetics and the Wright Fisher model in python?
1. Go through the given WFtrajectory function and give a short explanation of what each line of code does. Pay attention to the variables in the function and explain what they contain.
2. Make a new version of the WFtrajectory function which does exactly the same thing except that instead of appending to a list it initialises a numpy vector with zeroes and fills the vector with a for loop instead of a while loop. Make a plot of the output from a few example trajectories.
arrow_forward
Provide me complete and correct solution thanks 3
arrow_forward
Interpreter.java is missing these methods in the code so make sure to add them:
-print, printf: Exist, marked as variadic, call Java functions
-getline and next: Exist and call SplitAndAssign
-gsub, match, sub, index, length, split, substr, tolower, toupper: Exist, call Java functions, correct return
Below is interpreter.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Interpreter {
private HashMap<String, InterpreterDataType> globalVariables;
private HashMap<String, FunctionDefinitionNode> functions;
private class LineManager {
private List<String> lines;
private int currentLineIndex;
public LineManager(List<String> inputLines) {
this.lines = inputLines;
this.currentLineIndex = 0;
}
public boolean splitAndAssign() {
if (currentLineIndex < lines.size()) {
String currentLine = lines.get(currentLineIndex);…
arrow_forward
In this project, you will implement a Set class that represents a general collection of values. For this assignment, a set is generally defined as a list of values that are sorted and does not contain any duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that e1.equals(e2) and no null elements. (in java)Requirements among all implementations there are some requirements that all implementations must maintain. • Your implementation should always reflect the definition of a set. • For simplicity, your set will be used to store Integer objects. • An ArrayList<Integer> object must be used to represent the set. • All methods that have an object parameter must be able to handle an input of null. • Methods such as Collections. the sort that automatically sorts a list may not be used. Instead, when a successful addition of an element to the Set is done, you can ensure that the elements inside the ArrayList<Integer>…
arrow_forward
In this task you will work with the linked list of digits we have created in the lessons up to this point. As before you are provided with some code that you should not modify:
A structure definition for the storage of each digit's information.
A main() function to test your code.
The functions createDigit(), append(), printNumber(), freeNumber(), readNumber() and divisibleByThree() (although you may not need to use all of these).
Your task is to write a new function changeThrees() which takes as input a pointer that holds the address of the start of a linked list of digits. Your function should change all of those digits in this linked list that equal 3 to the digit 9, and count how many replacements were made. The function should return this number of replacements.
Provided code
arrow_forward
TaskDeclare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of…
arrow_forward
Develop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.Develop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.
arrow_forward
Write c++ code
Create a BST where each node stores the rollNumber and marks of a student. Your task is toprovide the implementation of following methods.constructorinsertRecord() functionupdateRecord() functioncountOfPassedStudents()showData() functioninside main() function, create an object of BST class.Insert the following data and create the BST according to the marks.● 19L-1941, 71 should be the root node● 19L-1942, 62● 19L-1943, 67● 19L-1944, 54● 19L-1945, 58● 19L-1946, 45● 19L-1947, 29● 19L-1948, 76● 19L-1949, 81● 19L-1950, 92Update the data of following record● Marks of 19L-1944 are 54. Update the marks to 47● Marks of 19L-1949 are 81. Update the marks to 85Call the countOfPassedStudents(). You can either display the count in the same function orreturn the value to main function.Call the showData() function to display all the records of BST in preorder traversal.Note: It is not mandatory to create a template class
arrow_forward
In C++, can I get a code example for a function that will return the intersection items for two sets. It will return/print out the shared (intersection) items for them. I am looking for an actual function preferably for a set class, comparing one instance of a set class with another, but definitely NOT a STL keyword. Thank you.
arrow_forward
Declare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of the…
arrow_forward
Declare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of the…
arrow_forward
Declare and implement 5 classes: FloatArray, SortedArray, FrontArray, PositiveArray & NegativeArray. 1- The FloatArray class stores a dynamic array of floats and its size. It has:- A parameterized constructor that takes the array size. - An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the array elements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size. - An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add to the array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size. - An add method that adds a float at the front…
arrow_forward
c++
student instruction1. SimpleVector Generic Template2. SearchableVector Generic Template3. SimpleVectorInterface Generic Template4. Soccer Class implemented with MyString 5. Implementation of operators.6. Use three files in your implementation.Description of the problem:1. Use the Soccer class described in Gaddis chapter 11 number 6 page 6522. Implement the operators in your code, and make the code modifications discussed in class, to create a one-dimensional array composed of instances of type Soccer and show your results in solving the following problems:to. (Gaddis) Programming Challenger 9. SearchableVectorModification page 1023 Chapter 16b. (Gaddis) Programming Challenger 10. SortableVector ClassTemplate Modification page 1023 Chap16. order with himSelection Sort algorithm p. 474 Chap. 8=============================================================== Soccer Scores class infoWrite a program that stores the following data about a soccer player in a structure: Player’s Name…
arrow_forward
Define buildListBackward function.
arrow_forward
dont write code. just write algorithm or related theory of the following question. Narrative 2: We need to have a generic module which reads in file and gives the output in the format which would facilitate other programs to do comparison like the one we saw above to carry out analysis and comparison. Response Required: Write a program that reads a given text, outputs the text as is, and also prints the number of lines and the number of times each letter appears in the text. An uppercase letter and a lowercase letter are treated as being the same; that is, they are tallied together. Since there are 26 letters, we use an array of 26 components to perform the letter count. We also need a variable to store the line count. The text is stored in a file, which we will call textin.txt. The output will be stored in a file, which we will call textout.txt Input: A file containing the text to be processed. Output: A file containing the text, number of lines, and the number of times a letter…
arrow_forward
Declare and implement 5 classes: FloatArray, SortedArray, FrontArray, PositiveArray & NegativeArray
1- The FloatArray class stores a dynamic array of floats and its size. It has:- A parameterized constructor that takes the array size. - An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the array elements from the file (ifstream) and add them to the array.- A destructor to deallocate the array
2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size. - An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add to the array then sort but rather add in the right place.
3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size. - An add method that adds a float at the front…
arrow_forward
Create a template class for a dynamic 1D array. You can model your class off of our Stringclass or the dynamic list class.
Changes from Stringclass:
You won't need an end-of-string element in the array.
The element type is now templated.
Translation will no longer be necessary.
operators - and -= 'might' now make sense (erase element(s)?).
...
Show how useful your template array class is by creating arrays of
short integers
doubles
Stringclass objects
(static) Pointclass objects
pointers to Pointclass objects (each allocated on the heap)
— all in one test application.
Make sure your test application is a good/thorough test of your class. (Your test application might utilize the applyand accumulatefunctions from lecture to facilitate testing. Also note how a typical template test application is structured — using templates to ease development.
arrow_forward
Please fill out the remaining codes in #TO-DO for Python:
import numpy as npimport pandas as pd
from sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorfrom sklearn.linear_model import LinearRegression
class MyLinearRegression:theta = None
def fit(self, X, y, option, alpha, epoch):X = np.concatenate((np.array(X), np.ones((X.shape[0], 1), dtype=np.float64)), axis=1)y = np.array(y)if option.lower() in ['bgd', 'gd']:# Run batch gradient descent.self.theta = self.batchGradientDescent(X, y, alpha, epoch)elif option.lower() in ['sgd']:# Run stochastic gradient descent.self.theta = self.stocGradientDescent(X, y, alpha, epoch)else:# Run solving the normal equation.self.theta = self.normalEquation(X, y)def predict(self, X):X = np.concatenate((np.array(X), np.ones((X.shape[0], 1), dtype=np.float64)), axis=1)if isinstance(self.theta, np.ndarray):# TO-DO: Implement predict().
return y_predreturn None
def…
arrow_forward
Write a function in Java. Also, write a JUnit test
Track basic input
the function should ask for input
add a Group
add a member with name, ID, age
Use arraylists
arrow_forward
In this project you will implement a Set class which represents a general collection of values. For this assignment, a set is generally defined as a list of values that is sorted and does not contain any duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that e1.equals(e2) and no null elements. Requirements To ensure consistency among all implementations there are some requirements that all implementations must maintain. • Your implementation should reflect the definition of a set at all times. • For simplicity, your set will be used to store Integer objects. • An ArrayList object must be used to represent the set. • All methods that have an object parameter must be able to handle an input of null. • Methods such as Collections.sort that automatically sort a list may not be used. • The Set class shall reside in the default package. Recommendations There are deviations in program implementation that are acceptable and will not impact the overall…
arrow_forward
In this project you will implement a Set class which represents a general collection of values. For this
assignment, a set is generally defined as a list of values that is sorted and does not contain any
duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that
e1.equals(e2) and no null elements.
Requirements
To ensure consistency among all implementations there are some requirements that all implementations
must maintain.
• Your implementation should reflect the definition of a set at all times.
• For simplicity, your set will be used to store Integer objects.
• An ArrayList<Integer> object must be used to represent the set.
• All methods that have an object parameter must be able to handle an input of null.
• Methods such as Collections.sort that automatically sort a list may not be used.
• The Set class shall reside in the default package.
Recommendations
There are deviations in program implementation that are acceptable and will not…
arrow_forward
In this project you will implement a Set class which represents a general collection of values. For this
assignment, a set is generally defined as a list of values that is sorted and does not contain any
duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that
e1.equals(e2) and no null elements.
Requirements
To ensure consistency among all implementations there are some requirements that all implementations
must maintain.
• Your implementation should reflect the definition of a set at all times.
• For simplicity, your set will be used to store Integer objects.
• An ArrayList<Integer> object must be used to represent the set.
• All methods that have an object parameter must be able to handle an input of null.
• Methods such as Collections.sort that automatically sort a list may not be used.
• The Set class shall reside in the default package.
Recommendations
There are deviations in program implementation that are acceptable and will not…
arrow_forward
Add the function min as an abstract function to the class arrayListType to return the smallest element of the list.
Also, write the definition of the function min in the class unorderedArrayListType and write a program to test this function.
I have 5 tabs:
I have tried every solution I can think of with no luck. These are the guides:
arrayListType.h
arrayListTypeImp.cpp:
main.cpp
unorderedArraryListType.h
unorderedArrayListTypeImp.cpp
I am needing these in order to pass the assignment in Cengage Mindtap, please help with codes for each one if possible.
arrow_forward
Write a Python Code for the given function and conditions:
Given function: def insert(self, newElement)
Pre-condition: None.
Post-condition: This method inserts newElement at the tail of the list. If an element with the same key as newElement already exists in the list, then it concludes the key already exists and does not insert the key.
arrow_forward
I really need help with this python question. You can't use break, str.endswith, list.index, keywords like: await, as, assert, class, except, lambda, and built in functions like: any, all, breakpoint, callable.
Write a recursive function:
def how_deep(list_struct):
You will be passed a list. However this is not a generic list, it will conform to these specific rules.
A list will either be:
Empty
A list of lists.
This means for example that a list can either be:
[], or [[],[],[]], or [[[],[],[],[[[]]]], []]
Our goal is to calculate the depth of these lists. It must be done recursively.
The depth of [] is 1 since it's a single list.
The depth of [[],[]] is 2 since there are lists within lists, but both of those lists are at the same depth.
The depth of [[[]],[],[[]],[[[]]]] is 4 because the first sublist is depth 2, then 1, then 2 again, and then 3. Therefore 1 + 3 = 4.
The depth of any list is considered to be the max of the depths of the sublists +…
arrow_forward
Make sure the program run smooth and perfectly, make sure no error encounter. compatible for python software.
Complete the sample code template to implement a student list as a binary search tree (BST).Specification1. Each Studentrecord should have the following fields: =studentNumber =lastname =firstName =course =gpa2. Run the program from an appropriate menu allowing for the following operations:* Adding a Student record
* Deleting a Student record
* Listing students by: • All students • A given course • GPA above a certain value • GPA below a certain value
class Record:def __init__(self, studentNumber = None, lastname = None, firstName = None, course = None, gpa =None,):self.studentNumber = studentNumberself.lastname = lastnameself.firstName = firstNameself.course = courseself.gpa = gpadef __str__(self):record = "\n\nStudent Number : {}\n".format(self.studentNumber)record += "Lastname : {}\n".format(self.lastname)record += "FirstName : {}\n".format(self.firstName)record…
arrow_forward
Java
(Sort, IComparable)
The librarian wants to sort the media in the
ArrayList by title.
For this purpose, the Medium class should
implement the Comparable interface.
Implement a Method compareTo (...) in the
abstract class Medium. Then sort the
Media in the ArrayList.
Implement the sort method in the
Zettelkasten class.This should, by
Parameters can be selected, the media
contained in descending ("A" → "Z") or
ascending ("Z" →
Sort "A") by title. Please do not implement
your own sorting algorithm, but rather
simply use a suitable method of the
ArrayList class.
Increase the efficiency of the note box. The
note box should remember whether the
The media contained therein are already
sorted, e.g. by calling sort earlier.
In this case, re-sorting should be omitted.
arrow_forward
Assignment: Implement Hot Potato Game in Python using the following:
List: Adam, Aziz, Rawan, Saeed, Nora, Faten, Waleed
Print the winner after 4 passes
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- Need help making a java file that combines both linearSearch and binarySearch •Both search methods must use the Comparable<T> interface and the compareTo() method.•Your program must be able to handle different data types, i.e., use generics.•For binarySearch, if you decide to use a midpoint computation formula that is different fromthe textbook, explain that formula briefly as a comment within your code. //code from textbook //linearSearch public static <T> boolean linearSearch(T[] data, int min, int max, T target) { int index = min; boolean found = false; while (!found && index <= max) { found = data [index].equals(target); index++; } return found; } //binarySearch public static <T extends Comparable<T>> boolean binarySearch(T[] data, int min, int max, T target) { boolean found = false; int midpoint = (min + max)/2; if (data[midpoint].compareTo(target)==0)…arrow_forwardHelp with c++... please paste indented code plzz and keep output same as givenarrow_forwardCan you help with with the following questions, regarding population genetics and the Wright Fisher model in python? 1. Go through the given WFtrajectory function and give a short explanation of what each line of code does. Pay attention to the variables in the function and explain what they contain. 2. Make a new version of the WFtrajectory function which does exactly the same thing except that instead of appending to a list it initialises a numpy vector with zeroes and fills the vector with a for loop instead of a while loop. Make a plot of the output from a few example trajectories.arrow_forward
- Provide me complete and correct solution thanks 3arrow_forwardInterpreter.java is missing these methods in the code so make sure to add them: -print, printf: Exist, marked as variadic, call Java functions -getline and next: Exist and call SplitAndAssign -gsub, match, sub, index, length, split, substr, tolower, toupper: Exist, call Java functions, correct return Below is interpreter.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Interpreter { private HashMap<String, InterpreterDataType> globalVariables; private HashMap<String, FunctionDefinitionNode> functions; private class LineManager { private List<String> lines; private int currentLineIndex; public LineManager(List<String> inputLines) { this.lines = inputLines; this.currentLineIndex = 0; } public boolean splitAndAssign() { if (currentLineIndex < lines.size()) { String currentLine = lines.get(currentLineIndex);…arrow_forwardIn this project, you will implement a Set class that represents a general collection of values. For this assignment, a set is generally defined as a list of values that are sorted and does not contain any duplicate values. More specifically, a set shall contain no pair of elements e1 and e2 such that e1.equals(e2) and no null elements. (in java)Requirements among all implementations there are some requirements that all implementations must maintain. • Your implementation should always reflect the definition of a set. • For simplicity, your set will be used to store Integer objects. • An ArrayList<Integer> object must be used to represent the set. • All methods that have an object parameter must be able to handle an input of null. • Methods such as Collections. the sort that automatically sorts a list may not be used. Instead, when a successful addition of an element to the Set is done, you can ensure that the elements inside the ArrayList<Integer>…arrow_forward
- In this task you will work with the linked list of digits we have created in the lessons up to this point. As before you are provided with some code that you should not modify: A structure definition for the storage of each digit's information. A main() function to test your code. The functions createDigit(), append(), printNumber(), freeNumber(), readNumber() and divisibleByThree() (although you may not need to use all of these). Your task is to write a new function changeThrees() which takes as input a pointer that holds the address of the start of a linked list of digits. Your function should change all of those digits in this linked list that equal 3 to the digit 9, and count how many replacements were made. The function should return this number of replacements. Provided codearrow_forwardTaskDeclare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of…arrow_forwardDevelop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.Develop a class ResizingArrayQueueOfStrings that implements the queueabstraction with a fixed-size array, and then extend your implementation to use arrayresizing to remove the size restriction.arrow_forward
- Write c++ code Create a BST where each node stores the rollNumber and marks of a student. Your task is toprovide the implementation of following methods.constructorinsertRecord() functionupdateRecord() functioncountOfPassedStudents()showData() functioninside main() function, create an object of BST class.Insert the following data and create the BST according to the marks.● 19L-1941, 71 should be the root node● 19L-1942, 62● 19L-1943, 67● 19L-1944, 54● 19L-1945, 58● 19L-1946, 45● 19L-1947, 29● 19L-1948, 76● 19L-1949, 81● 19L-1950, 92Update the data of following record● Marks of 19L-1944 are 54. Update the marks to 47● Marks of 19L-1949 are 81. Update the marks to 85Call the countOfPassedStudents(). You can either display the count in the same function orreturn the value to main function.Call the showData() function to display all the records of BST in preorder traversal.Note: It is not mandatory to create a template classarrow_forwardIn C++, can I get a code example for a function that will return the intersection items for two sets. It will return/print out the shared (intersection) items for them. I am looking for an actual function preferably for a set class, comparing one instance of a set class with another, but definitely NOT a STL keyword. Thank you.arrow_forwardDeclare and implement 5 classes: FloatArray, SortedArray,FrontArray, PositiveArray & NegativeArray.1- The FloatArray class stores a dynamic array of floats and itssize. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the end of the array.- Overloading for the insertion operator << to write the array to afile (ofstream)- Overloading for the extraction operator >> to read the arrayelements from the file (ifstream) and add them to the array.- A destructor to deallocate the array2- The SortedArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the right place in the arraysuch that the array remains sorted with every add. Don’t add tothe array then sort but rather add in the right place.3- The FrontArray inherits from FloatArray. It has:- A parameterized constructor that takes the array size.- An add method that adds a float at the front of the…arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- 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
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education