hw02
.pdf
keyboard_arrow_up
School
University of California, Berkeley *
*We aren’t endorsed by this school
Course
C100
Subject
Computer Science
Date
Feb 20, 2024
Type
Pages
9
Uploaded by CoachScienceRook44
hw02
February 4, 2024
[ ]:
# Initialize Otter
import
otter
grader
=
otter
.
Notebook(
"hw02.ipynb"
)
1
Homework 2: Arrays and Tables
Please complete this notebook by filling in the cells provided. Before you begin, execute the previous
cell to load the provided tests.
[ ]:
# Run this cell and ignore the output. It is checking to see if you ran the
␣
↪
first cell!
# If you get a NameError, please run the cell at the very TOP of this notebook!
grader
Helpful Resource:
-
Python Reference
: Cheat sheet of helpful array & table methods used in
Data 8!
Recommended Readings:
-
Arrays
-
What is Data Science?
-
Causality and Experiments
-
Programming in Python
For all problems that you must write explanations and sentences for, you
must
provide your
answer in the designated space. Moreover, throughout this homework and all future ones,
please
be sure to not re-assign variables throughout the notebook!
For example, if you use
max_temperature
in your answer to one question, do not reassign it later on. Otherwise, you will
fail tests that you thought you were passing previously!
Note: This homework has hidden tests on it. That means even though tests may say
100% passed, it doesn’t mean your final grade will be 100%. We will be running more
tests for correctness once everyone turns in the homework.
Directly sharing answers is not okay, but discussing problems with the course staff or with other
students is encouraged. Refer to the policies page to learn more about how to learn cooperatively.
You should start early so that you have time to get help if you’re stuck.
1
1.1
1. Creating Arrays
[ ]:
# Run this cell to set up the notebook, but please don't change it.
import
numpy
as
np
from
datascience
import
*
import
d8error
import
warnings
warnings
.
simplefilter(
'ignore'
,
FutureWarning
)
Question 1.
Make an array called
weird_numbers
containing the following numbers (in the given
order)
(4 Points)
:
1. -2
2. the floor of 12.6
3. 3
4. 5 to the power of the ceil of 5.3
Hint:
floor
and
ceil
are functions in the
math
module. Importing modules is covered in Lab 2!
Note:
Python lists are different/behave differently than NumPy arrays. In Data 8, we use NumPy
arrays, so please make an
array
, not a Python list.
[ ]:
# Our solution involved one extra line of code before creating
# weird_numbers.
...
weird_numbers
= ...
weird_numbers
[ ]:
grader
.
check(
"q1_1"
)
Question 2.
Make an array called
book_title_words
containing the following three strings:
“Eats”, “Shoots”, and “and Leaves”.
(4 Points)
[ ]:
book_title_words
= ...
book_title_words
[ ]:
grader
.
check(
"q1_2"
)
Strings have a method called
join
.
join
takes one argument, an array of strings.
It returns
a single string.
Specifically, the value of
a_string.join(an_array)
is a single string that’s the
concatenation
(“putting together”) of all the strings in
an_array
,
except
a_string
is inserted in
between each string.
Question 3.
Use the array
book_title_words
and the method
join
to make two strings
(4
Points)
:
1. “Eats, Shoots, and Leaves” (call this one
with_commas
)
2. “Eats Shoots and Leaves” (call this one
without_commas
)
2
Hint:
If
you’re
not
sure
what
join
does,
first
try
just
calling,
for
example,
"data8".join(book_title_words)
.
[ ]:
with_commas
= ...
without_commas
= ...
# These lines are provided just to print out your answers.
print
(
'with_commas:'
, with_commas)
print
(
'without_commas:'
, without_commas)
[ ]:
grader
.
check(
"q1_3"
)
1.2
2. Indexing Arrays
These exercises give you practice accessing individual elements of arrays. In Python (and in many
programming languages), each element is accessed by its
index
; for example, the first element is
the element at index 0. Indices must be
integers
.
Note:
If you have previous coding experience, you may be familiar with bracket
notation. DO NOT use bracket notation when indexing (i.e.
arr[0]
), as this can yield
different data type outputs than what we will be expecting. This can cause you to fail
an autograder test.
Be sure to refer to the
Python Reference
on the website if you feel stuck!
Question 1.
The cell below creates an array of some numbers. Set
third_element
to the third
element of
some_numbers
.
(4 Points)
[ ]:
some_numbers
=
make_array(
-1
,
-3
,
-6
,
-10
,
-15
)
third_element
= ...
third_element
[ ]:
grader
.
check(
"q2_1"
)
Question 2.
The next cell creates a table that displays some information about the elements of
some_numbers
and their order. Run the cell to see the partially-completed table, then fill in the
missing information (the cells that say “Ellipsis”) by assigning
blank_a
,
blank_b
,
blank_c
, and
blank_d
to the correct elements in the table.
(4 Points)
Hint:
Replace the
...
with strings or numbers. As a reminder, indices should be
integers
.
[ ]:
blank_a
= ...
blank_b
= ...
blank_c
= ...
blank_d
= ...
elements_of_some_numbers
=
Table()
.
with_columns(
"English name for position"
, make_array(
"first"
,
"second"
, blank_a,
␣
↪
blank_b,
"fifth"
),
"Index"
,
make_array(blank_c,
1
,
2
, blank_d,
4
),
3
"Element"
,
some_numbers)
elements_of_some_numbers
[ ]:
grader
.
check(
"q2_2"
)
Question 3.
You’ll sometimes want to find the
last
element of an array. Suppose an array has
142 elements. What is the index of its last element?
(4 Points)
[ ]:
index_of_last_element
= ...
[ ]:
grader
.
check(
"q2_3"
)
More often, you don’t know the number of elements in an array, its
length
. (For example, it might
be a large dataset you found on the Internet.) The function
len
takes a single argument, an array,
and returns an integer that represents the
len
gth of that array.
Question
4.
The
cell
below
loads
an
array
called
president_birth_years
.
Calling
tbl.column(...)
on a table returns an array of the column specified, in this case the
Birth Year
column of the
president_births
table. The last element in that array is the most recent among
the birth years of all the deceased Presidents. Assign that year to
most_recent_birth_year
.
(4
Points)
[ ]:
president_birth_years
=
Table
.
read_table(
"president_births.csv"
)
.
column(
'Birth
␣
↪
Year'
)
most_recent_birth_year
= ...
most_recent_birth_year
[ ]:
grader
.
check(
"q2_4"
)
Question 5.
Finally, assign
min_of_birth_years
to the minimum of the first, sixteenth, and last
birth years listed in
president_birth_years
.
(4 Points)
[ ]:
min_of_birth_years
= ...
min_of_birth_years
[ ]:
grader
.
check(
"q2_5"
)
1.3
3. Basic Array Arithmetic
Question 1.
Multiply the numbers 42, -4224, 424224242, and 250 by 157. Assign each variable
below such that
first_product
is assigned to the result of
42 ∗ 157
,
second_product
is assigned
to the result of
−4224 ∗ 157
, and so on.
(4 Points)
Note
: For this question,
don’t
use arrays.
[ ]:
first_product
= ...
second_product
= ...
third_product
= ...
4
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
*please help in java* Array testGrades contains NUM_VALS test scores. Write a for loop that sets sumExtra to the total extra credit received. Full credit is 100, so anything over 100 is extra credit. Ex: If testGrades = {101, 83, 107, 90}, then sumExtra = 8, because 1 + 0 + 7 + 0 is 8.
import java.util.Scanner;
public class SumOfExcess {public static void main (String [] args) {Scanner scnr = new Scanner(System.in);final int NUM_VALS = 4;int[] testGrades = new int[NUM_VALS];int i;int sumExtra = -9999; // Assign sumExtra with 0 before your for loop
for (i = 0; i < testGrades.length; ++i) {testGrades[i] = scnr.nextInt();}
// your answer goes here//
System.out.println("sumExtra: " + sumExtra);}}
arrow_forward
Finding the common members of two dynamic arrays: Write a program that first reads two arrays and then finds their common members (intersection). The program should first read an integer for the size of the array and then should create the two arrays dynamically (using new) and should read the numbers into array1 and array2 and then should find the common members and show it.
Note: The list of the common members should be unique. That is no member should be listed more than once.
Tip: A simple for loop is needed on one of the arrays (like array1) and one inner for loop for on array2. Then for each member of array1, if we find any matching member in array2, we record it.
Sample run:
Enter the number of elements of array 1: 7
Enter the elements of array 1: 10 12 13 10 14 15 12
Enter the number of elements of array 2: 5
Enter the elements of array 2: 17 12 10 19 12
The common members of array1 and array2 are: 12 10
arrow_forward
Probably 7.
arrow_forward
param data * @return true if all items of the array are positive (more than 0), false otherwise. * return false if the array is null. */
public boolean allPositives(int[] data)
without using functions
arrow_forward
Write pseudo code for given statemente.
The amount variable is set to 0, and then each is called on the array. Each of the values in the array is passed to the block. Each time the block is called, amount is updated:
arrow_forward
Assignment 5A: Multiple Frequencies. In the last assignment, we calculated the frequency of
a coin flip. This required us to have two separate variables, which we used to record the number
of heads and tails. Now that we know about arrays, we can track the frequency of all numbers in
a randomly generated sequence.
For this program, you will ask the user to provide a range of values (from 1 to that number,
inclusive) and how long of a number sequence you want to generate using that number range.
You will then generate and save the sequence in an array. After that, you will count the number
of times each number occurs in the sequence, and print the frequency of each number.
Hints: You can use multiple arrays for this assignment. One array should hold the
number sequence, and another could keep track of the frequencies of each number.
Sample Output #1:
What's the highest number you want to generate?: 5
How Long of a number sequence do you want to generate?: 10
Okay, we'll generate 10…
arrow_forward
do both tasks
arrow_forward
Rotate Right k cells (use python)
Consider an array named source. Write a method/function named rotateRight( source, k) that rotates all the elements of the source array to the right by 'k' positions. You must execute the method by passing an array and number of cells to be shifted. After calling the method, print the array to show whether the elements have been shifted properly.
Example:
source=[10,20,30,40,50,60]
rotateRight(source,3)
After calling rotateRight(source,3), printing the array should give the output as:
[ 40, 50, 60, 10, 20, 30]
arrow_forward
10
arrow_forward
Arrays
Write three statements to print the first three elements of array runTimes. Follow each statement with a newline. Ex: If runTime = {800, 775, 790, 805, 808}, print:800
775
790Note: These activities will test the code with different test values. This activity will perform two tests, both with a 5-element array (int runTimes[5]). See "How to Use zyBooks".Also note: If the submitted code tries to access an invalid array element, such as runTime[9] for a 5-element array, the test may generate strange results. Or the test may crash and report "Program end never reached", in which case the system doesn't print the test case that caused the reported message.
#include <iostream>using namespace std;
int main() {const int NUM_ELEMENTS = 5;int runTimes[NUM_ELEMENTS];int i;
for (i = 0; i < NUM_ELEMENTS; ++i) {cin >> runTimes[i];}
/* Your solution goes here */
return 0;}
Please help me with this problem using c++.
arrow_forward
Question Completion Status:
Write a Java program that uses ArrayList and Iterator, It should input from user the names and ages of your few
friends in a loop and add into ArrayList. Finally, it should use an terator to display the data in a proper format.
(Sample run of the program)
List of my Friends
Enter name and age [friend# 0]
Khalid Al-shamrí
22.5
Do you want to add another friend (y/ny? y
Enter name and age [friend# 1]
Rahsed Al anazi
21.1
Do you want to add another friend (y/ny? y
Enter name and age (friend# 2]
Salem Al mutaits
23.7
Click Save and Submit to save and submit. Click Save All Answers to save all answers.
Save A
arrow_forward
Bonus Question: For the same array as in the last question, explain what this statement does:
x = &x[2];
Hint: draw a memory diagram to help yourself find the correct answer.
arrow_forward
Problem 1 – Adding contactsIn this problem, you will create the skeleton for your entire assignment. In the next problems, you will add more functionality to your program.Our goal on this problem is to create a Rolodex to store names and e-mails (using 1D or 2D arrays, you can choose). The Rolodex can store up to 256 contacts. The Rolodex will store the contact's name as one String and the contact's e-mail as another String.Your application will work as follows:1. Upon starting, it will greet the user and prompt the user to select an option (an integer)2. There are three options in problem 1:1 – to add contactnote: If the Rolodex is full, i.e. there are 256 contacts stored, this option should print: "Roldex is Full" and ask the user to input a new option5 – to print all contacts0 – to exitIf the user inputs an incorrect value, the program should prompt for an option againIf the users select option 1:1. The application will then ask for the contact's name and e-mail (see the example for…
arrow_forward
Shift Right k Cells (Use Python)
Consider an array named source. Write a method/function named shifRight( source, k) that shifts all the elements of the source array to the right by 'k' positions. You must execute the method by passing an array and number of cells to be shifted. After calling the method, print the array to show whether the elements have been shifted properly.
Example:
source=[10,20,30,40,50,60]
shiftRight(source,3)
After calling shiftRight(source,3), printing the array should give the output as:
[ 0,0,0,10,20,30 ]
arrow_forward
For the array ADT, the operations associated with the type array are: insert a value in the array, delete a value from the array, and test whether a value is in the array or not.
1.true
2.false
arrow_forward
In main:
Declare an array capable of holding five Strings.
Populate the array by entering five first names all on one one line separated by spaces (see sample output but use different names).
Use a foreach loop (see page 255) to process the array and display the names on one line separated by spaces.
Pass the array to a void method.
In the void method:
Sort the array.
Create an arraylist of Strings.
Use a loop to populate the arraylist with the Strings in the array that was passed it.
Insert another name (you choose it) at the start of the arraylist.
Remove the name at the end of the arraylist.
Use a foreach loop to process the arraylist and display the names on one one line separated by spaces.
arrow_forward
Shift Left k Cells
Consider an array named source. Write a method/function named shiftLeft( source, k) that shifts all the elements of the source array to the left by 'k' positions. You must execute the method by passing an array and number of cells to be shifted. After calling the method, print the array to show whether the elements have been shifted properly.
Example:
source=[10,20,30,40,50,60]
shiftLeft(source,3)
After calling shiftLeft(source,3), printing the array should give the output as:
[ 40, 50, 60, 0, 0, 0 ]
arrow_forward
3. Implement a function called findLargestIndex which returns the index of the rowwith the largest sum.ex. int array[3][6] = {{3, 6, 8, 2, 4, 1}, // sum = 24{2, 4, 5, 1, 3, 4}, // sum = 19{1, 0, 9, 0, 1, 0}}; // sum = 11If the findLargestIndex function was called using this array, it would return 0, asit is returning the index of the row, not the sum.Note that the number of columns is required when passing a 2d array to a function.Assume that 2D arrays passed to this function will have 6 columns.Title line: int findLargestIndex(int array[][6], int rows, int columns);
arrow_forward
This is needed in JAVA
arrow_forward
3
E
Instructions
Write a program named
Averages that includes a
method named Average
that accepts any number
of numeric parameters,
displays them, and
displays their average.
For example, if 7 and 4
were passed to the
method, the output would
be:
74
Average is 5.
Test your function in your
Main (). Tests will be run
against Average () to
determine that it works
correctly when passed
one, two, or three
numbers, or an array of
numbers.
Averages.cs
1 using static System.Console;
2 public class Averages
3 {
4 public static void Main()
{
+56N
8
O
}
+
}
// Write your main here
arrow_forward
Q2:a) Which keyword is used to come out of a loop only for that iteration?
b) What is a array?
arrow_forward
1. Shift Left k Cells Use Python
Consider an array named source. Write a
method/function named shiftLeft( source, k)
that shifts all the elements of the source
array to the left by 'k' positions. You must
execute the method by passing an array
and number of cells to be shifted. After
calling the method, print the array to show
whether the elements have been shifted
properly.
Example:
source=[10,20,30,40,50,60]
shiftLeft(source,3)
After calling shiftLeft(source,3), printing the
array should give the output as:
[ 40, 50, 60, 0, 0, 0 ]
arrow_forward
//convert array of numbers from farenheit to celcius// example:// argument: [23, 32, 41, 50, 59]// return: [-5, 0, 5, 10, 15]// hint: use Array.mapfunction toCelcius(array){
}
//write a function that takes an input array and returns an array of booleans (>=75) or fail (<75)// example:// argument: [20, 30, 50, 80, 90, 100]// return: [false, false, false, true, true, true]// hint: use Array.mapfunction passOrFail(array){
}
arrow_forward
tfv
arrow_forward
Note: Please use WHILE LOOP and print all the contents of the array. Use java language.
Days of the Week. Create an array of Strings which are initialized to the 7 daysof the week. Use while-loop and print all the contents of the array.
arrow_forward
Code in C#
After the final exam, the following information is observed about securing “A” grade
PF class id 01 gets 4 A grades with scores 87 88 89 87
PF class id 02 gets 2 A grades with scores 90 87
PF class id 03 gets 3 A grades with scores 91 89 87
Write a program to store the above 3 class scores in Jagged Array by initialing all these values , then program will print the following information on screen.
1: Student with highest marks in each class
2: Student with highest marks in all 3 classes
arrow_forward
Explain the following in you own words:
a.) The relationship between loops and arrays.
b.) Provide example where you might use a loop to access an array to provide interactivity for a user.
arrow_forward
Task 01:
Assume P(x,y) is (x+y>4). Write a function/method that can validate the nested
quantifier Vy P(x,y) for elements from two arrays X and Y.
i.
hint:
The method returns l if statement is valid (the sum of all pairs of values from X and Y is greater than 4),
and returns 0 otherwise.
Valid case: For arrays X={2,3,4} and Y={3,4,5), the method returns 1(since xEX and býyEY, xi+y>4)
Invalid case: For arrays X={2,3,4} and Y={1,4.5}, the method returns 0 (since 2EX and l EY but 2+1<4)
arrow_forward
EX15: write
a program
that
return (1)
when
input number
odd
return (2) when input number is even
5/7
EX16: write a program that separate the content of a
input array (a)
into
two
arrays;
(x) : contain
the
6/7
numbers with odd index and other array (y) contain
numbers with even index .
EX17:let you have array A[20], write a program that
read the array and swap the content of odd index with
7/7
the content of even index .
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming with Microsoft Visual Basic 2017
Computer Science
ISBN:9781337102124
Author:Diane Zak
Publisher:Cengage Learning
Related Questions
- *please help in java* Array testGrades contains NUM_VALS test scores. Write a for loop that sets sumExtra to the total extra credit received. Full credit is 100, so anything over 100 is extra credit. Ex: If testGrades = {101, 83, 107, 90}, then sumExtra = 8, because 1 + 0 + 7 + 0 is 8. import java.util.Scanner; public class SumOfExcess {public static void main (String [] args) {Scanner scnr = new Scanner(System.in);final int NUM_VALS = 4;int[] testGrades = new int[NUM_VALS];int i;int sumExtra = -9999; // Assign sumExtra with 0 before your for loop for (i = 0; i < testGrades.length; ++i) {testGrades[i] = scnr.nextInt();} // your answer goes here// System.out.println("sumExtra: " + sumExtra);}}arrow_forwardFinding the common members of two dynamic arrays: Write a program that first reads two arrays and then finds their common members (intersection). The program should first read an integer for the size of the array and then should create the two arrays dynamically (using new) and should read the numbers into array1 and array2 and then should find the common members and show it. Note: The list of the common members should be unique. That is no member should be listed more than once. Tip: A simple for loop is needed on one of the arrays (like array1) and one inner for loop for on array2. Then for each member of array1, if we find any matching member in array2, we record it. Sample run: Enter the number of elements of array 1: 7 Enter the elements of array 1: 10 12 13 10 14 15 12 Enter the number of elements of array 2: 5 Enter the elements of array 2: 17 12 10 19 12 The common members of array1 and array2 are: 12 10arrow_forwardProbably 7.arrow_forward
- param data * @return true if all items of the array are positive (more than 0), false otherwise. * return false if the array is null. */ public boolean allPositives(int[] data) without using functionsarrow_forwardWrite pseudo code for given statemente. The amount variable is set to 0, and then each is called on the array. Each of the values in the array is passed to the block. Each time the block is called, amount is updated:arrow_forwardAssignment 5A: Multiple Frequencies. In the last assignment, we calculated the frequency of a coin flip. This required us to have two separate variables, which we used to record the number of heads and tails. Now that we know about arrays, we can track the frequency of all numbers in a randomly generated sequence. For this program, you will ask the user to provide a range of values (from 1 to that number, inclusive) and how long of a number sequence you want to generate using that number range. You will then generate and save the sequence in an array. After that, you will count the number of times each number occurs in the sequence, and print the frequency of each number. Hints: You can use multiple arrays for this assignment. One array should hold the number sequence, and another could keep track of the frequencies of each number. Sample Output #1: What's the highest number you want to generate?: 5 How Long of a number sequence do you want to generate?: 10 Okay, we'll generate 10…arrow_forward
- do both tasksarrow_forwardRotate Right k cells (use python) Consider an array named source. Write a method/function named rotateRight( source, k) that rotates all the elements of the source array to the right by 'k' positions. You must execute the method by passing an array and number of cells to be shifted. After calling the method, print the array to show whether the elements have been shifted properly. Example: source=[10,20,30,40,50,60] rotateRight(source,3) After calling rotateRight(source,3), printing the array should give the output as: [ 40, 50, 60, 10, 20, 30]arrow_forward10arrow_forward
- Arrays Write three statements to print the first three elements of array runTimes. Follow each statement with a newline. Ex: If runTime = {800, 775, 790, 805, 808}, print:800 775 790Note: These activities will test the code with different test values. This activity will perform two tests, both with a 5-element array (int runTimes[5]). See "How to Use zyBooks".Also note: If the submitted code tries to access an invalid array element, such as runTime[9] for a 5-element array, the test may generate strange results. Or the test may crash and report "Program end never reached", in which case the system doesn't print the test case that caused the reported message. #include <iostream>using namespace std; int main() {const int NUM_ELEMENTS = 5;int runTimes[NUM_ELEMENTS];int i; for (i = 0; i < NUM_ELEMENTS; ++i) {cin >> runTimes[i];} /* Your solution goes here */ return 0;} Please help me with this problem using c++.arrow_forwardQuestion Completion Status: Write a Java program that uses ArrayList and Iterator, It should input from user the names and ages of your few friends in a loop and add into ArrayList. Finally, it should use an terator to display the data in a proper format. (Sample run of the program) List of my Friends Enter name and age [friend# 0] Khalid Al-shamrí 22.5 Do you want to add another friend (y/ny? y Enter name and age [friend# 1] Rahsed Al anazi 21.1 Do you want to add another friend (y/ny? y Enter name and age (friend# 2] Salem Al mutaits 23.7 Click Save and Submit to save and submit. Click Save All Answers to save all answers. Save Aarrow_forwardBonus Question: For the same array as in the last question, explain what this statement does: x = &x[2]; Hint: draw a memory diagram to help yourself find the correct answer.arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTProgramming with Microsoft Visual Basic 2017Computer ScienceISBN:9781337102124Author:Diane ZakPublisher:Cengage Learning
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming with Microsoft Visual Basic 2017
Computer Science
ISBN:9781337102124
Author:Diane Zak
Publisher:Cengage Learning