hw05

pdf

School

University of California, Berkeley *

*We aren’t endorsed by this school

Course

C8

Subject

Computer Science

Date

Dec 6, 2023

Type

pdf

Pages

8

Uploaded by AdmiralAtom103517

Report
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
Stanford | 41 | 11 … (2 rows omitted) [14]: grader . check( "q1_2" ) [14]: q1_2 results: All test cases passed! We can get specific row objects from a table. You can use tbl.row(n) to get the n th row of a table. row.item("column_name") will allow you to select the element that corresponds to column_name in a particular row. Here’s an example: [15]: # Just run this cell # We got the Axe! games . row( 9 ) # <-- this will return a row object [15]: Row(Opponent='Stanford', Cal 1Q=0, Cal 2Q=14, Cal 3Q=13, Cal 4Q=14, Opp 1Q=0, Opp 2Q=3, Opp 3Q=0, Opp 4Q=8) [16]: # Just run this cell games . row( 9 ) . item( "Cal 4Q" ) # <-- this will return a item (e.g. an int) from a row object [16]: 14 Question 3. We want to see for a particular game whether or not Cal lost. Write a function called did_cal_lose . It should take one argument: a row object from the final_scores table. It should return either True if Cal’s score was less than the Opponent’s score, and False otherwise. (5 Points) Note 1 : “Row object” means a row from the table extracted (behind the scenes) using tbl.row(index) that contains all the data for that specific row. It is not the index of a row. Do not try and call final_scores.row(row) inside of the function. Note 2 : If you’re still confused by row objects, try printing out final_scores.row(1) in a new cell to visually see what it looks like! This piece of code is pulling out the row object located at index 1 of the final_scores table and returning it. When you display it in a cell, you’ll see that it is not located within a table, but is instead a standalone row object! [19]: def did_cal_lose (row): return ( row . item( "Cal Score" ) < row . item( "Opponent Score" ) ) did_cal_lose(final_scores . row( 1 )) #DO NOT CHANGE THIS LINE [19]: True [20]: grader . check( "q1_3" ) [20]: q1_3 results: All test cases passed! 4
Question 4. James wants to see how Cal did against every opponent during the 2021 season. Using the final_scores table: 1. Assign results_array to an array of True and False values that correspond to whether or not Cal lost. 2. Add results_array to the final_scores table in a column named Results , and assign this to final_scores_with_results . 3. Then, respectively assign the number of wins and losses Cal had to cal_wins and cal_losses . (10 Points) Hint : tbl.apply() might be helpful. Refer to the Python Reference if you’re unsure how it works! [23]: results_array = final_scores . apply(did_cal_lose) final_scores_with_results = final_scores . with_columns( "Results" ,results_array) cal_losses = final_scores_with_results . where( "Results" ,are . equal_to( True )) . num_rows cal_wins = final_scores_with_results . where( "Results" ,are . equal_to( False )) . num_rows # Don't delete or edit the following line: print ( f"In the 2021 Season, Cal Football won { cal_wins } games and lost { cal_losses } games. Go Bears! ￿" ) In the 2021 Season, Cal Football won 5 games and lost 7 games. Go Bears! ￿ [24]: grader . check( "q1_4" ) [24]: q1_4 results: All test cases passed! 1.3 2. Unrolling Loops (Optional) This section of HW5 is optional. Do it for your own practice, but it will not be incorporated into the final grading! “Unrolling” a for loop means to manually write out all the code that it executes. The result is code that does the same thing as the loop, but without the structure of the loop. For example, for the following loop: for num in np.arange(3): print("The number is", num) The unrolled version would look like this: print("The number is", 0) print("The number is", 1) print("The number is", 2) Unrolling a for loop is a great way to understand what the loop is doing during each step. In this exercise, you’ll practice unrolling a for loop. 5
In the question below, write code that does the same thing as the given code, but with any for loops unrolled. It’s a good idea to run both your answer and the original code to verify that they do the same thing. (Of course, if the code does something random, you’ll get a different random outcome than the original code!) Optional Question 1. Unroll the code below. [25]: for joke_iteration in range ( 3 ): print ( "Knock. " * (joke_iteration + 1 )) print ( "Who's there?" ) print ( "Banana." ) print ( "Banana who?" ) print ( "Knock, knock." ) print ( "Who's there?" ) print ( "Orange." ) print ( "Orange who?" ) print ( "Orange you glad I didn't say banana?" ) Knock. Who's there? Banana. Banana who? Knock. Knock. Who's there? Banana. Banana who? Knock. Knock. Knock. Who's there? Banana. Banana who? Knock, knock. Who's there? Orange. Orange who? Orange you glad I didn't say banana? [27]: print ( "Knock. " * 1 ) print ( "Who's there?" ) print ( "Banana." ) print ( "Banana who?" ) print ( "Knock. " * 2 ) print ( "Who's there?" ) print ( "Banana." ) print ( "Banana who?" ) print ( "Knock. " * 3 ) print ( "Who's there?" ) print ( "Banana." ) print ( "Banana who?" ) 6
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
print ( "Knock, knock." ) print ( "Who's there?" ) print ( "Orange." ) print ( "Orange who?" ) print ( "Orange you glad I didn't say banana?" ) Knock. Who's there? Banana. Banana who? Knock. Knock. Who's there? Banana. Banana who? Knock. Knock. Knock. Who's there? Banana. Banana who? Knock, knock. Who's there? Orange. Orange who? Orange you glad I didn't say banana? Congratulations, you are done with Homework 5! Important submission steps: 1. Run the tests and verify that they all pass. 2. Choose Save Notebook from the File menu, then run the final cell . 3. Click the link to download the zip file. 4. Go to Gradescope and submit the zip file to the corresponding assignment. The name of this assignment is “HW 05 Autograder”. 1.4 Pets of Data 8 Mel says congrats on finishing Homework 5! Pet of the week: Mel 1.5 Submission Make sure you have run all cells in your notebook in order before running the cell below, so that all images/graphs appear in the output. The cell below will generate a zip file for you to submit. Please save before exporting! [28]: # Save your notebook first, then run this cell to export your submission. grader . export(pdf = False , run_tests = True ) 7
Running your submission against local test cases… Your submission received the following results when run against available test cases: q0_1 results: All test cases passed! q1_1 results: All test cases passed! q1_2 results: All test cases passed! q1_3 results: All test cases passed! q1_4 results: All test cases passed! <IPython.core.display.HTML object> 8