hw05
.pdf
keyboard_arrow_up
School
University of California, Berkeley *
*We aren’t endorsed by this school
Course
C8
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
8
Uploaded by AdmiralAtom103517
hw05
November 30, 2023
[1]:
# Initialize Otter
import
otter
grader
=
otter
.
Notebook(
"hw05.ipynb"
)
1
Homework 5: Applying Functions and Iteration
Please complete this notebook by filling in the cells provided. Before you begin, execute the previous
cell to load the provided tests.
Helpful Resource:
-
Python Reference
: Cheat sheet of helpful array & table methods used in
Data 8!
Recommended Readings
:
•
Tabular Thinking Guide
•
Applying Functions
•
Conditionals
•
Iteration
Please complete this notebook by filling in the cells provided.
Before you begin, execute the
cell below to setup the notebook by importing some helpful libraries.
Each time you
start your server, you will need to execute this cell again.
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!
Deadline:
This assignment is
due Wednesday, 2/27 at 11:00pm PT
. Turn it in by Tuesday, 2/26 at
11:00pm PT for 5 extra credit points. Late work will not be accepted as per the
policies
page.
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.
1
You should start early so that you have time to get help if you’re stuck.
Offce hours are held
Monday through Friday in
Warren Hall
101B. The offce hours schedule appears
here
.
1.1
0. Midterm Accommodations Form
Question 1.
The DATA C8 Fall 2023 Midterm Exam will take place on
Friday, October 13th
from 7PM - 9PM PT
. Please complete this form so that we can best accommodate you for the
midterm.
All students are required to fill out this form
. The deadline to submit this form
is
Saturday, October 7th by 11:59PM.
The link can be found below.
(1 Point)
•
Fall 2023 Midterm Accommodations Survey
Assign
secret_phrase
to the secret phrase given at the end of the accommodations survey. Make
sure the phrase is in quotes (i.e. is a string)!
[4]:
secret_phrase
=
"jason"
[5]:
grader
.
check(
"q0_1"
)
[5]:
q0_1 results: All test cases passed!
1.2
1. 2021 Cal Football Season
[6]:
# Run this cell to set up the notebook, but please don't change it.
# These lines import the Numpy and Datascience modules.
import
numpy
as
np
from
datascience
import
*
# These lines do some fancy plotting magic.
import
matplotlib
%
matplotlib
inline
import
matplotlib.pyplot
as
plt
plt
.
style
.
use(
'fivethirtyeight'
)
import
warnings
warnings
.
simplefilter(
'ignore'
,
FutureWarning
)
James is trying to analyze how well the Cal football team performed in the 2021 season.
A
football game is divided into four periods, called quarters.
The number of points Cal scored in
each quarter and the number of points their opponent scored in each quarter are stored in a table
called
cal_fb.csv
.
[7]:
# Just run this cell
# Read in the cal_fb csv file
games
=
Table()
.
read_table(
"cal_fb.csv"
)
games
.
show()
<IPython.core.display.HTML object>
Let’s start by finding the total points each team scored in a game.
2
Question 1.
Write a function called
sum_scores
.
It should take four arguments, where each
argument represents integers corresponding to the team’s score for each quarter. It should return
the team’s total score for that game.
(2 Points)
Hint:
Don’t overthink this question!
[10]:
def
sum_scores
(q1,q2,q3,q4):
'''Returns the total score calculated by adding up the score of each
␣
↪
quarter'''
return
(q1
+
q2
+
q3
+
q4)
sum_scores(
14
,
7
,
3
,
0
)
#DO NOT CHANGE THIS LINE
[10]:
24
[11]:
grader
.
check(
"q1_1"
)
[11]:
q1_1 results: All test cases passed!
Question
2.
Create a new table
final_scores
with three columns in this
specific
order:
Opponent
,
Cal Score
,
Opponent Score
.
You will have to create the
Cal Score
and
Opponent
Score
columns.
Use the function
sum_scores
you just defined in the previous question for this
problem.
(5 Points)
Hint:
If you want to apply a function that takes in multiple arguments, you can pass multiple column
names as arguments in
tbl.apply()
.
The column values will be passed into the corresponding
arguments of the function. Take a look at the Python Reference Sheet and Lecture 13’s demo for
syntax.
Note:
If you’re running into issues creating
final_scores
, check that
cal_scores
and
opp_scores
output what you want. If you’re encountering
TypeError
s, check the
Python Reference
to see if
the inputs/outputs of the function are what you expect.
[13]:
cal_scores
=
games
.
apply(sum_scores,
"Cal 1Q"
,
"Cal 2Q"
,
"Cal 3Q"
,
"Cal 4Q"
)
opp_scores
=
games
.
apply(sum_scores,
"Opp 1Q"
,
"Opp 2Q"
,
"Opp 3Q"
,
"Opp 4Q"
)
final_scores
=
games
.
with_columns(
"Cal Score"
, cal_scores,
"Opponent Score"
,
␣
↪
opp_scores)
.
select(
"Opponent"
,
"Cal Score"
,
"Opponent Score"
)
final_scores
[13]:
Opponent
| Cal Score | Opponent Score
Nevada
| 17
| 22
TCU
| 32
| 34
Sacramento State | 42
| 30
Washington
| 24
| 31
Washington State | 6
| 21
Oregon
| 17
| 24
Colorado
| 26
| 3
Oregon State
| 39
| 25
Arizona
| 3
| 10
3
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
code output
arrow_forward
Programming Language: C++
Please output it in the console not a text file.
For this exerc ise, you will define a struct. It will contain a first name, last name, ID, and GPA. You will ask the user how many students to enter, create a dynamic
array of that size to get data from the user. The array data will initially be inserted into the array in ID order. Then you will display the array in a table, sort it by last
name with std::sort, redisplay it, and then search for five students (using last name and a binary search) and for any names found display the first name, last name,
and GPA,
The struct will be named Student and include strings for firstName, lastName, ID, and a float for the GPA. The ID will be in the format 00xxxxxx where the x's are
replaced by digits and in the range between 111111 and 999999. The GPA will be a floating-point number in the range 2.0 to 4.2 and will be displayed to 2 digits
after the decimal point.
arrow_forward
Problem Attached
arrow_forward
*Reasking a question to make request clearer
Looking to code in python the following:
Suppose the weekly hours for all employees are stored in a table.
Each row records an employee’s seven-day work hours with seven columns. For example, the following table stores the work hours for eight employees.
Su M T W Th F Sa Employee 0 2 4 3 4 5 8 8 Employee 1 7 3 4 3 3 4 4 Employee 2 3 3 4 3 3 2 2 Employee 3 9 3 4 7 3 4 1 Employee 4 3 5 4 3 6 3 8 Employee 5 3 4 4 6 3 4 4 Employee 6 3 7 4 8 3 8 4 Employee 7 6 3 5 9 2 7 9
I need a program that inputs the hours of all employees by the user and displays employees and their total hours in decreasing order of the total hours.
Thanks
arrow_forward
please help me with the pseudocode of the program for the project.
Need a class which will contain:
Student Name
Student Id
Student Grades (an array of 3 grades)
A constructor that clears the student data (use -1 for unset grades)
Get functions for items a, b, and c, average, and letter grade
Set functions for items a, n, and c
Note that the get and set functions for Student grades need an argument for the grade index.
Need another class which will contain:
An Array of Students (1 above)
A count of number of students in use
You need to create a menu interface that allows you to:
Add new students
Enter test grades
Display all the students with their names, ids, test grades, average, and letter grade
Exit the program
Add comments and use proper indentation.
Nice Features:
I would like that system to accept a student with no grades, then later add one or more grades, and when all grades are entered, calculate the final average or grade.
I would like the system to display the…
arrow_forward
Please add an execution chart for this code like the example below. I have provided the code and the example execution chart. :
Sample Execution Chart Template//your header files// constant size of the array// declare an array of BankAccount objects called accountsArray of size =SIZE// comments for other declarations with variable names etc and their functionality// function prototypes// method to fill array from file, details of input and output values and purpose of functionvoid fillArray (ifstream &input,BankAccount accountsArray[]);// method to find the largest account using balance as keyint largest(BankAccount accountsArray[]);// method to find the smallest account using balance as keyint smallest(BankAccount accountsArray[]);// method to display all elements of the accounts arrayvoid printArray(BankAccount accountsArray[]);int main() {// function calls come here:// give the function call and a comment about the purpose,// and input and return value if any//open file//fill…
arrow_forward
Write a function to determine the resultant force vector R of the two forces F₁ and F2 applied to the bracket, where 0₁ and 02. Write
R in terms of unit vector along the x and y axis. R must be a vector, for example R = [Rx, Ry]. The coordinate system is shown in
the figure below:
F₁
y
0₂
0₁
F2
arrow_forward
Question no 01: Mr. Patrick is fond of reading books he is looking for a computerized way to keep record of hisbook collection, you have been given the responsibility to meet up his following requirements.(Use appropriate data structure to accomplish your task), develop following methods:1. Add(): adds a new book to the list ( A book contains name of the book, author name)NOTE: every new book will have access to its neighboring books (previous and next)2. Remove():in case any book is removed from the pile update your list 3. countBooks(): displays the total number of books 4. search(): returns true if the given book is present in the list else returns false 5. display(): shows the book collection
arrow_forward
DESIGN YOUR OWN SETTING
Task 5: Devise your own setting for storing and searching the data in an array of non-negative integers redundantly. You may just describe the setting without having to give an explicit algorithm to explain the process by which data is stored. You should explain how hardware failures can be detected in your method. Once you have described the setting, complete the following:
Write a pseudocode function to describe an algorithm where the stored data can be searched for a value key: if the data is found, its location in the original array should be returned; -1 should be returned if the data is not found; -2 should be returned if there is a data storage error
Include a short commentary explaining why your pseudocode works
Describe the worst-case and best-case inputs to your search algorithm
Derive the worst-case and best-case running times for the search algorithm
Derive the Theta notation for the worst-case and best-case running times
Maximum word…
arrow_forward
Homework Assignment-1Topics: Functions, Dictionary, ImportProblem description: Write a python application to simulate an online clothing system. Thepurpose of this assignment is to gain experience in Python dictionary structure, create basicPython functions and import a module.Design solution: The template file contains a list of clothes item sold, each item in the listcontains the item id, name of the item and the prices. The program will generate an items_dictwhere each key is the item id of the cloth and the values will be a list of item name and priceinformation. A customer will be presented with a main menu with 4 different options: displayall items, add an item to cart, checkout and exit the program. A customer can buy an item byentering the ID of the item. This program implements a dictionary called cart, where each key isthe item id and the values are the list of name, price and quantity that user chooses topurchase. The program keeps repeating by displaying the main menu to…
arrow_forward
Q3] Create a new function with the name DrawHPyramid that takes one parameter r, which is the
number of rows. This function rather than using the ghạracter it uses + and - to draw the pyramid,
use recursion when implementing this function
arrow_forward
Functions with 2D Arrays in Java
Write a function named displayElements that takes a two-dimensional array, the size of its rows and columns, then prints every element of a two-dimensional array. Separate every row by a new line and every column by a space.
In the main function, call the displayElements function and pass in the required parameters.
Output
1 2 3
4 5 6
7 8 9
arrow_forward
C# Programming
See attached photo for the problem needed to be fixed.
Please make my code correct without changing the IEnumerable<string> in the function because it is crucial to my code. I need this code to be corrected and if you do, I owe you a big thank you and good rating. Thank you so much for your help in advance!
arrow_forward
Must show it in Python:Please show step by step with comments.Please show it in simplest form.Please don't use any functionsPlease don't use any def func ()Input and Output must match with the QuestionPlease go through the Question very carefully.
arrow_forward
Must show it in Python:Please show step by step with comments.Please show it in simplest form.Please don't use any functionsPlease don't use any def func ()Input and Output must match with the QuestionPlease go through the Question very carefully.
arrow_forward
- ### Question 18
Write a R code to do this calculation with a logistic regression model. Compute a CI of this OR.
You will use the arrays xp and yp built above.
First use the glm function to fit a logistic regression model using of yp versus xp. Save the
model to an object named mp:
Paste your R code in BOX 1 [Format:a30]
`{r}
Use the exp, cbind and coef function to calculate the odds ratios (intercept and xp) and their
95% confidence intervals, as done in the preparation lab.
Paste your R code in BOX 2 [Format:a35]
{r}
arrow_forward
Exercise, maxCylinderVolume
F# system function such as min or methods in the list module such as List.map are not allowed
Write a function maxCylinderVolume that takes a list of floating-point tuples that represent dimensions of a cylinder and returns the volume of the cylinder that has the largest volume. Each tuple has two floating point values that are both greater than zero. The first value is the radius r and the second value is the height h. The volume of the cylinder is computed using ??2h. The value π is represented in F# with System.Math.PI. If the list is empty, return 0.0.
Examples:
> maxCylinderVolume [(2.1, 3.4); (4.7, 2.8); (0.9, 6.1); (3.2, 5.4)];;val it : float = 194.3137888> maxCylinderVolume [(0.33, 0.66)];;val it : float = 0.2257988304
arrow_forward
Dynamic Array Functions XLOOKUP What is one characteristic of the XLOOKUP) function that makes it so flexible?
OPTIONS:
It can only take dynamic arrays as input
It can be used to lookup data both vertically and horizontally
It always returns a matrix of data
It takes only one input parameter
arrow_forward
The following array of structures is used to hold data of your IPC144 grade center
strcut grades {char name[101]; unsigned final; unsigned total;}
struct grades myClass[25];
Write a function that gets the class grades array as a parameter and prints the list of people who passed the course (a student passes a course if he/she passes the final as well as the total) and their total mark. The function should also print the class average at the end (based on the total marks)
void printPassedAverage(struct grades myClass, int size)
The output should be like this
Students passed:---------------------
John Smith 85
Jane Doe 65
Roy Crowe 80
Julia Stuart 55
Rob Gates 60
Class average: 69
arrow_forward
use javascript
arrow_forward
Assignment Pointers & Classes1- Define a class student with the following fields:a. First nameb. Last namec. IDd. Number of courses enrolled ine. Dynamic array of courses (taken and currently enrolled in): String *coursesf. Dynamic array of grades: int* gradesg. Addressh. Registration feesi. Total number of creditsj. Expected Graduation term.2- Declare an array of four students. Perform the following operations using your declared array:a. Open the provided file input.txt. Fill the array by reading values from the specified inputfile. Make sure that the array of courses and array of grades are initialized properly anddestroyed properly as well.b. Call a function that prints student information in a well-organized table like fashion.c. Call a function that compares average between two students.d. Call a function that prints student names based on their GPA from highest to lowest.(hint you need to sort the array of students).e. Call a function that prints student names from lowest…
arrow_forward
Objective: Write a Java program practicing the use of arrays in addition to the other programming practices you have learned, such as program decomposition and the use of Java class (static) methods. Monolithic solutions that do not exhibit good design practices and appropriate class methods will not receive full credit.
Use arrays for this. Do not use ArrayLists.
Material Provided: You will need the following file to complete this lab:
info.txt (A sample input file, which is available on Carmen.)
Set up
You will need to create your own implementation of the Student class. It will look much like the Student class we saw in the class PowerPoint slides. You may take some shortcuts though. Knowing that the data will always be sets of four lines of text which contain a student name and three scores, you can get away with a constructor that takes the name and three scores and creates the instance of the Student object. (You will still need to get the data out of it though,…
arrow_forward
Prompt: In Python language, wrte a function that applies the logistic sigmoid function to all elements of a NumPy array.
Code:
import numpy as np
import math
import matplotlib.pyplot as plt
import pandas as pd
def sigmoid(inputArray):
modifiedArray = np.zeros(len(inputArray))
#YOUR CODE HERE:
return(modifiedArray)
def test():
inputs = np.arange(-100, 100, 0.5)
outputs = sigmoid(inputs)
plt.figure(1)
plt.plot(inputs)
plt.title('Input')
plt.xlabel('Index')
plt.ylabel('Value')
plt.show()
plt.figure(2)
plt.plot(outputs,'Black')
plt.title('Output')
plt.xlabel('Index')
plt.ylabel('Value')
plt.show()
test()
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
Related Questions
- code outputarrow_forwardProgramming Language: C++ Please output it in the console not a text file. For this exerc ise, you will define a struct. It will contain a first name, last name, ID, and GPA. You will ask the user how many students to enter, create a dynamic array of that size to get data from the user. The array data will initially be inserted into the array in ID order. Then you will display the array in a table, sort it by last name with std::sort, redisplay it, and then search for five students (using last name and a binary search) and for any names found display the first name, last name, and GPA, The struct will be named Student and include strings for firstName, lastName, ID, and a float for the GPA. The ID will be in the format 00xxxxxx where the x's are replaced by digits and in the range between 111111 and 999999. The GPA will be a floating-point number in the range 2.0 to 4.2 and will be displayed to 2 digits after the decimal point.arrow_forwardProblem Attachedarrow_forward
- *Reasking a question to make request clearer Looking to code in python the following: Suppose the weekly hours for all employees are stored in a table. Each row records an employee’s seven-day work hours with seven columns. For example, the following table stores the work hours for eight employees. Su M T W Th F Sa Employee 0 2 4 3 4 5 8 8 Employee 1 7 3 4 3 3 4 4 Employee 2 3 3 4 3 3 2 2 Employee 3 9 3 4 7 3 4 1 Employee 4 3 5 4 3 6 3 8 Employee 5 3 4 4 6 3 4 4 Employee 6 3 7 4 8 3 8 4 Employee 7 6 3 5 9 2 7 9 I need a program that inputs the hours of all employees by the user and displays employees and their total hours in decreasing order of the total hours. Thanksarrow_forwardplease help me with the pseudocode of the program for the project. Need a class which will contain: Student Name Student Id Student Grades (an array of 3 grades) A constructor that clears the student data (use -1 for unset grades) Get functions for items a, b, and c, average, and letter grade Set functions for items a, n, and c Note that the get and set functions for Student grades need an argument for the grade index. Need another class which will contain: An Array of Students (1 above) A count of number of students in use You need to create a menu interface that allows you to: Add new students Enter test grades Display all the students with their names, ids, test grades, average, and letter grade Exit the program Add comments and use proper indentation. Nice Features: I would like that system to accept a student with no grades, then later add one or more grades, and when all grades are entered, calculate the final average or grade. I would like the system to display the…arrow_forwardPlease add an execution chart for this code like the example below. I have provided the code and the example execution chart. : Sample Execution Chart Template//your header files// constant size of the array// declare an array of BankAccount objects called accountsArray of size =SIZE// comments for other declarations with variable names etc and their functionality// function prototypes// method to fill array from file, details of input and output values and purpose of functionvoid fillArray (ifstream &input,BankAccount accountsArray[]);// method to find the largest account using balance as keyint largest(BankAccount accountsArray[]);// method to find the smallest account using balance as keyint smallest(BankAccount accountsArray[]);// method to display all elements of the accounts arrayvoid printArray(BankAccount accountsArray[]);int main() {// function calls come here:// give the function call and a comment about the purpose,// and input and return value if any//open file//fill…arrow_forward
- Write a function to determine the resultant force vector R of the two forces F₁ and F2 applied to the bracket, where 0₁ and 02. Write R in terms of unit vector along the x and y axis. R must be a vector, for example R = [Rx, Ry]. The coordinate system is shown in the figure below: F₁ y 0₂ 0₁ F2arrow_forwardQuestion no 01: Mr. Patrick is fond of reading books he is looking for a computerized way to keep record of hisbook collection, you have been given the responsibility to meet up his following requirements.(Use appropriate data structure to accomplish your task), develop following methods:1. Add(): adds a new book to the list ( A book contains name of the book, author name)NOTE: every new book will have access to its neighboring books (previous and next)2. Remove():in case any book is removed from the pile update your list 3. countBooks(): displays the total number of books 4. search(): returns true if the given book is present in the list else returns false 5. display(): shows the book collectionarrow_forwardDESIGN YOUR OWN SETTING Task 5: Devise your own setting for storing and searching the data in an array of non-negative integers redundantly. You may just describe the setting without having to give an explicit algorithm to explain the process by which data is stored. You should explain how hardware failures can be detected in your method. Once you have described the setting, complete the following: Write a pseudocode function to describe an algorithm where the stored data can be searched for a value key: if the data is found, its location in the original array should be returned; -1 should be returned if the data is not found; -2 should be returned if there is a data storage error Include a short commentary explaining why your pseudocode works Describe the worst-case and best-case inputs to your search algorithm Derive the worst-case and best-case running times for the search algorithm Derive the Theta notation for the worst-case and best-case running times Maximum word…arrow_forward
- Homework Assignment-1Topics: Functions, Dictionary, ImportProblem description: Write a python application to simulate an online clothing system. Thepurpose of this assignment is to gain experience in Python dictionary structure, create basicPython functions and import a module.Design solution: The template file contains a list of clothes item sold, each item in the listcontains the item id, name of the item and the prices. The program will generate an items_dictwhere each key is the item id of the cloth and the values will be a list of item name and priceinformation. A customer will be presented with a main menu with 4 different options: displayall items, add an item to cart, checkout and exit the program. A customer can buy an item byentering the ID of the item. This program implements a dictionary called cart, where each key isthe item id and the values are the list of name, price and quantity that user chooses topurchase. The program keeps repeating by displaying the main menu to…arrow_forwardQ3] Create a new function with the name DrawHPyramid that takes one parameter r, which is the number of rows. This function rather than using the ghạracter it uses + and - to draw the pyramid, use recursion when implementing this functionarrow_forwardFunctions with 2D Arrays in Java Write a function named displayElements that takes a two-dimensional array, the size of its rows and columns, then prints every element of a two-dimensional array. Separate every row by a new line and every column by a space. In the main function, call the displayElements function and pass in the required parameters. Output 1 2 3 4 5 6 7 8 9arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage Learning
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning