How does Generics and Parameterized classes promote reusability, give an example?
In: Computer Science
def get_words(filename):
'''
(str) -> list of str
Given the name of a file which contains many words
(one word per line), return a list of all these words.
The file may have comments and a blank space at the beginning
of the file, which should be ignored. All comment lines start
with
a semicolon ';'.
'''
Python
In: Computer Science
Consider the following code. Explain what this code does and determine the output. Let us discuss.
#include <iostream>
using namespace std;
int top;
void check (char str[ ], int n, char stack [ ])
{
for(int i = 0 ; i < n ; i++ )
{
if (str [ i ] == ‘(’)
{
top = top + 1;
stack[ top ] = ‘ ( ’;
}
if(str[ i ] == ‘)’ )
{
if(top == -1 )
{
top = top -1 ;
break ;
}
else
{
top = top -1 ;
}
}
}
if(top == -1)
cout << “String is balanced!” << endl;
else
cout << “String is unbalanced!” << endl ;
}
int main ( )
{
char str[ ] = { ‘(‘ , ‘a’ , ‘+’, ‘ ( ’, ‘b ’ , ‘-’ , ‘ c’ ,‘)’ , ‘
) ’} ;
char str1 [ ] = { ‘(’ , ‘(’ , ‘a’ , ‘ + ’ , ‘ b’ , ‘)’ } ;
char stack [ 15 ] ;
top = -1;
check (str , 9 , stack ); //Passing balanced string
top = -1 ;
check(str1 , 5 , stack) ; //Passing unbalanced string
}
In: Computer Science
Javascript/HTML/CSS Problem
(Only use pure javascript, DO NOT USE ANY JAVASCRIPT FRAMEWORKS)
Create a non-predictive T9-like keypad. For those who do not know what a T9 keypad looks like, use the following shell in an html file to get a sense of what it looked like on pre-smart cellular phones:
<h3>T9 Keypad</h3>
<input id="in" type="text"/>
<br>
<button>abc</button>
<button>def</button>
<br>
<button>ghi</button>
<button>jkl</button>
<button>mno</button>
<br>
<button>pqrs</button>
<button>tuv</button>
<button>wxyz</button>
<script>
// your code here
</script>
How it functions for the assignment:
* If a button contains a letter you want to type, click on the
button N number of times associated to the order the letters are
in. So if you wanted "c", you push the second button 3 times.
* If you push the button more than the number of letters in the
button, it will wrap-around and return the letter after. For
example, clicking the first button 5 times returns "b".
* (Bonus 5 points) The input field only shows the letter once
you've completed a sequence of < 500 ms clicks. If you stop
clicking for > 500 ms, the letter associated with the number of
clicks so far, is appended to the input string.
In: Computer Science
Suppose we have a dataset DD in a regression problem.
What will happen to the in-sample error of linear regression using polynomials of degree dd as d→∞d→∞?
What will happen to the out-of-sample error of linear regression as dd increases?
You can use the output of the code below to help you form your answer.
CODE BELOW:
xmin,xmax = 0,4*np.pi
x = np.linspace(xmin,xmax,1000)
D = 14
N = 100
shuff = np.random.permutation(len(x))
x_pts = np.array(sorted(x[shuff][:N]))
K = 200
train_vals = np.zeros(D*K).reshape(K,D)
test_vals = np.zeros(D*K).reshape(K,D)
noise = np.random.randn(N)
y = np.sin(x_pts)+ noise/7
for k in range(K):
shuff = np.random.permutation(len(x))
x_pts = np.array(sorted(x[shuff][:N]))
noise = np.random.randn(N)
y = np.sin(x_pts)+ noise/7
for i,deg in enumerate(range(D)):
X = np.ones(N*deg).reshape(N,deg)
for j in range(1,deg):
X[:,j] = x_pts**j
X_train,X_test,y_train,y_test = test_train_split(X,y,0.13)
w = linear_fit(X_train,y_train)
g_train = linear_predict(X_train,w)
g_test = linear_predict(X_test,w)
r_train = RMSE(g_train,y_train)
r_test = RMSE(g_test,y_test)
train_vals[k][i] = r_train
test_vals[k][i] = r_test
tr_vals = np.mean(train_vals,axis=0)
te_vals = np.mean(test_vals,axis=0)
plt.plot(range(D),tr_vals)
plt.title("In sample error as a function of model complexity")
plt.xlabel("Polynomial degree")
plt.ylabel("RMSE")
plt.show()
plt.title("Out of sample error as a function of model complexity")
plt.plot(range(D),te_vals)
plt.xlabel("Polynomial degree")
plt.ylabel("RMSE")
plt.axis([0,D,0,2])
plt.show()In: Computer Science
Pls decode the following question and then solve it.
O BR DNOCQOCM FL B DNTII KMOD CGRJIT. WNIC WTODDIC OC JBUI IOMND, DNI CGRJIT UDOEE NBU DNTII KOMODU, JGD DNIY BTI IXBADEY DNI TIVITUI FL ODU JBUI DIC TIHTIUICDBDOFC. WNBD OU DNI CGRJIT?
Note: all the signle letter = I or A
In: Computer Science
1. If the 4-bit two's complement representations of integers J and K are 0100 and 1001, respectively, then the decimal representation of integer (J - K) (K subtracted from J) is
2. The "correctness" core quality of software refers to the fact that ...
3. Running class TwoDSum, whose code is:
public class TwoDSum {
public static void main(String[] args) {
int[][] table =
{-1,7,-3},{0,2,-4},{9,-6,5};
int sum = 0;
for (int i = 0; i < table.length;
i++)
if (i !=
table.length - i)
sum += table[i][i] + table[table.length - i-1][i];
System.out.println("Sum is " + sum);
}
}
will display on the user console ...
4. The code of class Det below:
public class Det {
public static void main(String[] args) {
int[][] a = new int[2][];
a[0] = new int[2];
a[1] = new int[2];
a[0][0] = 2;
a[0][1] = 1;
a[1][0] = 5;
a[1][1] = 3;
int det = a[0][0]*a[1][1] -
a[0][1]*a[1][0];
System.out.println("Determinant
is " + det);
}
}
will ...
5. Given the two code fragments A) an B), below, to compute the final value of a variable grandTotal, of type double and a 0 initial value:
A)
double delta = 0.1;
for (int i=0; i<10000; i++)
grandTotal += delta;
B)
double delta = 0.001;
for (int i=0; i<1000000; i++)
grandTotal += delta;
Then variable grandTotal is...
6. An interface...
In: Computer Science
Design a simple C program using ordinary pipes in which a parent
and child processes
exchange greeting messages. For example, the parent process may
send the message
“Hello child have you complete the task”, and the child process may
return “Yes
Parent I have completed the task”. Use Unix/Linux pipes to write
this program.
In: Computer Science
Caesar’s cipher is a very well known and simple encryption scheme. The point of an encryption scheme is to transform a message so that only those authorized will be able to read it. Caesar’s cipher conceals a message by replacing each letter in the original message (the plaintext), by a letter corresponding to a certain number of letters to the right on the alphabet. Of course, the message can be retrieved by replacing each letter in the encoded message (the ciphertext) with the letter corresponding to the same number of position to the left on the alphabet. To achieve this, the cipher has a key that needs to be kept private. Only those with the key can encode and decode a message. Such a key determines the shift that needs to be performed on each letter. For example, here is how a string containing the entire alphabet will be encrypted using a key equal to 3: Original: abcdefghijklmnopqrstuvwxyz Encrypted: defghijklmnopqrstuvwxyzabc Vigen`ere’s cipher is a slightly more complex encryption scheme, also used to transform a message. Thekey of this cipher consists of a word and the cipher works by applying multiple Caesar ciphers based on the letters of the keyword. Each letter can be associated with a number corresponding to its position in the English alphabet (counting from 0). For instance, the letter ‘a’ is associated to 0, ‘c’ to 2, and ‘z’ to 25. Therefore, the keyword of the cipher will provide as many integers as letters in the word and these integers will be used to implement different Caesar ciphers. Let’s see how: suppose the message to encrypt is “elephants” and the keyword is “rats”. The first thing to do is to repeat the keyword until its length matches the one of the message. Message: e l e p h a n t s Keyword: r a t s r a t s r Now, each letter of “ratsratsr” is associated to both a letter in the message and an integer. We can encrypt each letter of the message using a Caesar cipher where the key corresponds to the integer associated to it through the keyword. In this case ‘r’ corresponds to 17, so the first letter of the message which is an ‘e’ will be encrypted using a ‘v’, the second letter ‘l’ as an ‘l’ since ‘a’ is associated to 0, and so on. The entire message will be encrypted as “vlxhyaglj”. The goal of this exercise is to write several methods in order to create a program that encodes and decodes messages using Caesar’s and Vigen`ere’s ciphers. For the purpose of this exercise we will only consider messages written using lower case letters and blank spaces. All the code for this question must be placed in a file named Cipher.java. 2a. Encoding a character Let’s start by writing a simple method called charRightShift which takes a character and an integer n as inputs, and returns a character. The method should verify that the integer is a number between 0 and 25 (both included). If that’s not the case, the method should print out an error message and return the character with ASCII value 0. Note that ASCII value 0 is not ’0’, but is the char that maps to the value 0! Otherwise, if the character received as input is a lower case letter of the English alphabet, the method will return the letter of the alphabet which is n positions to the right on the alphabet. If the character received as input is not a lower case letter of the English alphabet, then the method returns the character itself with no modification. For example: • charRightShift(‘g’, 2 ) returns ‘i’, • charRightShift(‘#’, 2 ) returns ‘#’, and • charRightShift(‘h’, 32 ) returns the character with ASCII 0 and prints an error message. 2b. Decoding a character Write a method charLeftShift which practically reverses what the previous method does. This method also takes a character and an integer n as inputs, and returns a character. The method should verify that the integer is a number between 0 and 25 (both included). If that’s not the case it should print out an error message and return the character with ASCII value 0. Note that ASCII value 0 is not ’0’, but is the char that maps to the value 0! Otherwise, if the character received as input is a lower case letter of the English alphabet, the method will return the letter of the alphabet which is n positions to the left on the alphabet. If the character received as input is not a lower case letter of the English alphabet, then the method returns the character itself with no modification. For example: • charLeftShift(‘i’, 2 ) returns ‘g’, • charLeftShift(‘#’, 2 ) returns ‘#’, and Page 6 • charLeftShift(‘h’, 32 ) returns the character with ASCII 0 and prints an error message. Note: The two methods above are very similar. This suggests that you write one common method charShift which contains the shifting logic and can shift both left and right. Then charRightShift can simply call charShift with a positive n, and charLeftShift can call charShift with a negative version of n. 2c. Caesar’s cipher - Encoding Write a method caesarEncode that takes a String message and an int key as inputs and returns the string obtained by encrypting message using the Caesar’s cipher with key equal to key. To create the encrypted string you need to replace each letter in message, by the letter corresponding to key letters to the right on the alphabet. You should call and use charRightShift appropriately in order to get full points. The input key must be an integer from 0 to 25 (included). Your method should print out an error message and return the empty string if that’s not the case. For the purpose of this exercise you can assume that the strings to encrypt will only contain letters from the English alphabet in lower case and blank spaces. Blank spaces don’t get modified by the encryption. For example, caesarEncode(‘‘cats and dogs’’, 5) should return ‘‘hfyx fsi itlx’’. 2d. Caesar’s cipher - Decoding Write a method caesarDecode that takes a String message and an int key as inputs and retunrs the string obtained by decrypting message using the Caesar’s cipher with key equal to key. To decrypt the string you need to replace each letter in message, by the letter corresponding to key letters to the left on the alphabet. To get full points, you should call and use the method charLeftShift appropriately. As for caesarEncode, the key must be a number between 0 and 25. Your method should print an error message and return an empty string if that’s not the case. More over, you can expect strings to contain only lower case letters from the English alphabet and blank spaces which will not be modified by the decryption (as they were not modified by the encryption). For example, caesarDecode(‘‘hfyx fsi itlx’’, 5) should return ‘‘cats and dogs’’. 2e. From String to keys Write a method called obtainKeys which takes a String as input and returns an array of integers. The size of the array will be equal to the length of the String. The elements of the array correspond to the position (counting from 0) of each character in the String as a letter of the English alphabet. For instance obtainKeys(‘‘hello’’) returns [7, 4, 11, 11, 14]. For the purpose of this exercise you can assume that the input String to this method will only contain lower case letters of the English alphabet. 2f. Vigen`ere’s cipher - Encoding Write a method vigenereEncode that takes a String message and a String keyword as inputs and returns the string obtained by encrypting message using the Vigen`ere’s cipher with key equal to keyword. Remember that this cipher first associates each letter of the keyword to a letter of the message. Then it shifts (to the right) each letter of the message by the number of positions determined by the corresponding letter in the keyword. Use the methods obtainKeys and charRightShift appropriately in order to implement the encryption.The input keyword must contain only characters from the lower case English alphabet. Your method should print out an error message and return the empty string if that’s not the case. For the purpose of this exercise you can assume that the strings to encrypt will only contain letters from the English alphabet in lower case and blank spaces. Blank spaces don’t get modified by the encryption. For example, vigenereEncode(‘‘elephants and hippos’’, ‘‘rats’’) should return ‘‘vlxhyaglj tfu aagphk’’. 2g. Vigen`ere’s cipher - Decoding Finally, write a method vigenereDecode that takes a String message and a String keyword as inputs and returns the string obtained by decrypting the message using the Vigen`ere’s cipher with key equal to keyword. Remember that this cipher first associates each letter of the keyword to a letter of the message. Then it shifts (to the left) each letter of the message by the number of positions determined by the corresponding letter in the keyword. Use the methods obtainKeys and charLeftShift appropriately in order to implement the decryption. Again, the input keyword must contain only characters from the lower case English alphabet. Your method should print out an error message and return the empty string if that’s not the case. For the purpose of this exercise you can assume that the strings to decrypt will only contain letters from the English alphabet in lower case and blank spaces. For example, vigenereDecode(‘‘vlxhyaglj tfu aagphk’’, ‘‘rats’’) should return ‘‘elephants and hippos’’.
In: Computer Science
In: Computer Science
I am just learning C++ and need to convert my previous code to a new linked list method. Please help.
My current LL program:
#include
#include
using namespace std;
struct LLnode{
string theData;
LLnode * fwdPtr;
};
void push_front(LLnode * &llh, string newData{
if(!llh){
LLnode * newNode = new LLnode;
newNode -> theData = newData;
newNode -> fwdPtr = nullptr;
llh = newNode;
}
else{
LLnode * trav = new LLnode;
trav = llh;
LLnode * newNode = new LLnode;
newNode -> theData = newData;
newNode -> fwdPtr = trav;
llh = newNode;
}
}
void push_back(LLnode * &llh, string newData){
LLnode * trav = new LLnode;
if(!llh){
llh = new LLnode;
llh -> theData = newData;
llh -> fwdPtr = nullptr;
}
else{
LLnode * newNode = new LLnode;
newNode -> theData = newData;
newNode -> fwdPtr = nullptr;
trav = llh;
while(trav -> fwdPtr){
trav = trav -> fwdPtr;
}
trav -> fwdPtr = newNode;
}
}
int list_length(LLnode * &llh){
int count = 0;
LLnode * trav = new LLnode;
trav = llh;
if(!llh){
return 0;
}
else{
while(trav){
count ++;
trav = trav -> fwdPtr;
}
return count;
}
}
string retrieve_front (LLnode * &llh){
if(!llh)
throw string ("Exception at retrieve back");
return (llh -> theData);
}
string retrieve_back (LLnode * &llh){
LLnode * trav = new LLnode;
trav = llh;
if(!llh)
throw string ("Exception at retrieve back");
while(trav -> fwdPtr){
trav = trav -> fwdPtr;
}
return trav -> theData;
}
void display_nodes(LLnode * &llh) {
LLnode * trav = new LLnode;
trav = llh;
if(!llh){
cout << "No nodes to display " << endl;
}
else{
cout << "Displaying nodes: " << endl;
while(trav){
cout << trav -> theData << ", ";
trav = trav -> fwdPtr;
}
}
cout << endl;
}
int main(){
LLnode * theLLHeader1 = nullptr;
cout << "Main: number of nodes in empty list " <<
list_length(theLLHeader1) << endl;
display_nodes(theLLHeader1);
push_front(theLLHeader1, "aaaaa");
push_back(theLLHeader1, "bbbbb");
push_front(theLLHeader1, "before aaaaa");
push_back(theLLHeader1, "after bbbbb");
cout << "Main: number of nodes after 4 pushed: " <<
list_length(theLLHeader1) << endl;
display_nodes(theLLHeader1);
cout << "Main: retrieve front: " << retrieve_front
(theLLHeader1) << endl;
cout << "Main: retrieve back: " << retrieve_back
(theLLHeader1) << endl;
cout << endl;
LLnode * theLLHeader2 = nullptr;
push_front(theLLHeader2, "33333");
push_front(theLLHeader2, "22222");
push_front(theLLHeader2, "11111");
push_back(theLLHeader2, "44444");
push_back(theLLHeader2, "55555");
push_back(theLLHeader2, "66666");
display_nodes (theLLHeader2);
return 0;
}
What I need to do:
Step 1
Convert LLnode struct into a header file. Any code module that refers to LLnode will need to contain a #include for this header file.
Create a linked list class named LL. Put into the same header file as struct. It will contain private data member: a linked list header, which is just a pointer variable of type LLnode for LLnode variables
I have already coded six linked list processing functions – push_front, push_back, list_length, retrieve_front, retrieve_back, and display_list. I need to convert these functions into public member functions of the class. The constructor for the LL class should set the linked list header to nullptr. There is no destructor. I also need to Templatize the class, and a requirement for templatized class functions is that they be coded in-line in the class definition. So, code the member functions in-line within the header file. You’ll have only two course files: the header file, and the .cpp for main.
I would like evidence of Couts so I can better understand the program. This would be much appreciated.
Step 2
Using a class template, I need to change struct and class to use any variable type. Main # 2 has been set up for debugging this step.
Step 3
Add member functions that perform the following functions:
void destroy_list ()
deletes each node in the list, and resets the header to nullptr
bool search_list (key value)
searches the list for a node with the given key. Returns true if
found, false if not.
bool delete_node (key value)
deletes the node which contains the given key. If there is more
than one node with the same key, delete_node deletes the first
occurrence. Returns true if delete successful, false if the node
was not found.
Main # 3 contains a test program for testing step 3.
Here are the main classes (1,2,3)::
//MAIN 1
int main() {
LL ll1;
cout << "length of empty list - " << ll1.list_length()
<< endl;
ll1.display_list();
ll1.push_front("aaaaa");
ll1.push_back("bbbbb");
ll1.push_front("before aaaaa");
ll1.push_back("after bbbbb");
cout << "length of list after 4 pushes - " <<
ll1.list_length() << endl;
ll1.display_list();
cout << endl;
LL ll2;
ll2.push_front("33333");
ll2.push_front("22222");
ll2.push_front("11111");
ll2.push_back("44444");
ll2.push_back("55555");
ll2.push_back("66666");
ll2.display_list();
return 0;
}
//MAIN 2
int main() {
LL ll1;
cout << "main: length of empty list - " <<
ll1.list_length() << endl;
cout << "main: trying to display empty list 1" <<
endl;
ll1.display_list();
cout << "main: trying to display initial size of ll1 - "
<< ll1.list_length() << endl;
ll1.push_front("aaaaa");
ll1.push_back("bbbbb");
ll1.push_front("before aaaaa");
ll1.push_back("after bbbbb");
cout << "main: length of ll1 after 4 pushes - " <<
ll1.list_length() << endl;
cout << "main: now trying to display ll1 after 4 push's"
<< endl;
ll1.display_list();
cout << "main: displaying final size of ll1 - " <<
ll1.list_length() << endl;
cout << endl;
LL ll2;
ll2.push_front("33333");
ll2.push_front("22222");
ll2.push_front("11111");
ll2.push_back("44444");
ll2.push_back("55555");
ll2.push_back("66666");
cout << "main: now trying to display ll2 after 6 push's"
<< endl;
ll2.display_list();
return 0;
}
//MAIN 3
int main() {
LL ll1;
cout << "main: length of empty list - " <<
ll1.list_length() << endl;
cout << "main: trying to display empty list 1" <<
endl;
ll1.display_list();
cout << "main: trying to display initial size of ll1 - "
<< ll1.list_length() << endl;
ll1.push_front("aaaaa");
ll1.push_back("bbbbb");
ll1.push_front("before aaaaa");
ll1.push_back("after bbbbb");
cout << "main: length of ll1 after 4 pushes - " <<
ll1.list_length() << endl;
cout << "main: now trying to display ll1 after 4 push's"
<< endl;
ll1.display_list();
cout << "main: displaying final size of ll1 - " <<
ll1.list_length() << endl;
ll1.destroy_list();
cout << "main: displaying size of list 1 after destroy - "
<< ll1.list_length() << endl;
cout << endl;
LL ll2;
ll2.push_front("33333");
ll2.push_front("22222");
ll2.push_front("11111");
ll2.push_back("44444");
ll2.push_back("55555");
ll2.push_back("66666");
cout << "main: now trying to display ll2 after 6 push's"
<< endl;
ll2.display_list();
cout << "main: now searching for node 44444" <<
endl;
if (ll2.search_list("44444"))
{
cout <<"main: found node 44444" << endl;
}
else
{
cout << "main: did not find node 44444" << endl;
}
cout << "main: now searching for node 44445" <<
endl;
if (ll2.search_list("44445"))
{
cout <<"main: found node 44445" << endl;
}
else
{
cout << "main: did not find node 44445" << endl;
}
cout << "main: now trying to delete node 44444" <<
endl;
if (ll2.delete_node("44444"))
{
cout <<"main: node 44444 deleted" << endl;
}
else
{
cout << "main: did not find 44444 for delete" <<
endl;
}
if (ll2.search_list("44444"))
{
cout <<"main: searched for 44444 after delete, found"
<< endl;
}
else
{
cout << "main: searched for 44444 after delete, not found"
<< endl;
}
cout << "main: displaying whole list after delete 44444"
<< endl;
ll2.display_list();
cout << "main: now trying to delete node 11111" <<
endl;
if (ll2.delete_node("11111"))
{
cout <<"main: node 11111 deleted" << endl;
}
else
{
cout << "main: did not find node 11111 for delete" <<
endl;
}
cout << "main displaying whole list after delete 11111"
<< endl;
ll2.display_list();
ll2.destroy_list();
return 0;
}
I will much appreciate any help. Thank you.
In: Computer Science
JAVA:
Write a program that converts a binary number to decimal (integer)
Based on user input: Ask user to input a binary number
Conditions:
Check that the binary number starts with a 1 and only has 0s and 1s
If condition is not met, ask for user to reenter a number
Conver the binary to decimal (integer)
Ask user if they want to input another number if not then the program will exit
*Please do not use built-in java functions when converting binary to decimal
In: Computer Science
Write the program with language C++ ( THE PROGRAM SHOULD CONTAIN DECISION MAKING , LOOPING AND A FUNCTION ) to design a menu for a shop . When the user makes a choice , ask for quantity, then display the total charge with sale taxes . If the user enters a choice that is unavailable ,display an error message and ask him to re-enter.
In: Computer Science
You are to implement a string compression algorithm with the following specifications:
Create a function RLE() to implement this algorithm recursively, this function should take in a string message and return the compressed string as an output.
Python code
In: Computer Science
All in MIPS assembly
1. Have the user input a 32 bit binary string
2. convert that into decimal
3. Print the decimal
In: Computer Science