hw02

pdf

School

University of North Georgia, Dahlonega *

*We aren’t endorsed by this school

Course

MATH-240

Subject

Mathematics

Date

Apr 3, 2024

Type

pdf

Pages

10

Uploaded by ProfessorStarCheetah74

Report
hw02 February 3, 2024 1 Homework 2: Arrays and Tables [1]: # Don't change this cell; just run it. # When you log-in please hit return (not shift + return) after typing in your , email import numpy as np from datascience import * Recommended Reading : * Data Types * Sequences * Tables Please complete this notebook by filling in the cells provided. 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. Before continuing the assignment, select “Save and Checkpoint” in the File menu. 1.1 1. Creating Arrays Question 1. Make an array called weird_numbers containing the following numbers (in the given order): 1. -2 2. the sine of 1.2 3. 3 4. 5 to the power of the cosine of 1.2 Hint: sin and cos are functions in the math module. 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. [3]: # Our solution involved one extra line of code before creating # weird_numbers. ... weird_numbers = make_array( -2 , math . sin( 1.2 ), 3 , 5** math . cos( 1.2 )) weird_numbers Question 2. Make an array called book_title_words containing the following three strings: “Eats”, “Shoots”, and “and Leaves”. 1
[5]: book_title_words = ... book_title_words 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: 1. “Eats, Shoots, and Leaves” (call this one with_commas ) 2. “Eats Shoots and Leaves” (call this one without_commas ) Hint: If you’re not sure what join does, first try just calling, for example, "foo".join(book_title_words) . [13]: with_commas = ... without_commas = ... # These lines are provided just to print out your answers. print ( 'with_commas:' , with_commas) print ( 'without_commas:' , without_commas) 1.2 2. Indexing Arrays These exercises give you practice accessing individual elements of arrays. In Python (and in many programming languages), elements are accessed by index , so the first element is the element at index 0. Note: Please don’t use bracket notation when indexing (i.e. arr[0] ), as this can yield different data type outputs than what we will be expecting. Question 1. The cell below creates an array of some numbers. Set third_element to the third element of some_numbers . [4]: some_numbers = make_array( -1 , -3 , -6 , -10 , -15 ) third_element = some_numbers . item( 2 ) third_element , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-4-fe05151aa25c> in <module> ----> 1 some_numbers = make_array(-1, -3, -6, -10, -15) 2 2
3 third_element = some_numbers.item(2) 4 third_element NameError: name 'make_array' is not defined 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. [5]: blank_a = "third" blank_b = "fourth" blank_c = 0 blank_d = 3 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 ), "Element" , some_numbers) elements_of_some_numbers , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-5-dc5ed62ee7ec> in <module> 3 blank_c = 0 4 blank_d = 3 ----> 5 elements_of_some_numbers = Table().with_columns( 6 "English name for position", make_array("first", "second", , blank_a, blank_b, "fifth"), 7 "Index", make_array(blank_c, 1, 2, blank_d, , 4), NameError: name 'Table' is not defined 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? [6]: index_of_last_element = 141 More often, you don’t know the number of elements in an array, its length . (For example, it might 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
be a large dataset you found on the Internet.) The function len takes a single argument, an array, and returns the len gth of that array (an integer). Question 4. The cell below loads an array called president_birth_years . Calling .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 birth year of any deceased president. Assign that year to most_recent_birth_year . [7]: president_birth_years = Table . read_table( "president_births.csv" ) . column( 'Birth , Year' ) most_recent_birth_year = president_birth_years . item( 37 ) most_recent_birth_year , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-7-91220221d27d> in <module> ----> 1 president_birth_years = Table.read_table("president_births.csv"). , column('Birth Year') 2 3 most_recent_birth_year = president_birth_years.item(37) 4 most_recent_birth_year NameError: name 'Table' is not defined Question 5. Finally, assign sum_of_birth_years to the sum of the first, tenth, and last birth year in president_birth_years . [8]: sum_of_birth_years = (president_birth_years . item( 0 ) + president_birth_years . , item( 9 ) + president_birth_years . item( 37 )) , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-8-95e4dcd565ee> in <module> ----> 1 sum_of_birth_years = (president_birth_years.item(0) + , president_birth_years.item(9) + president_birth_years.item(37)) 4
NameError: name 'president_birth_years' is not defined 1.3 3. Basic Array Arithmetic Question 1. Multiply the numbers 42, 4224, 42422424, 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. For this question, don’t use arrays. [9]: first_product = 42 * 157 second_product = 4224 * 157 third_product = 42422424 * 157 fourth_product = -250 * 157 print (first_product, second_product, third_product, fourth_product) 6594 663168 6660320568 -39250 Question 2. Now, do the same calculation, but using an array called numbers and only a single multiplication ( * ) operator. Store the 4 results in an array named products . [10]: numbers = make_array ( 42 , 4224 , 42422424 , -250 ) products = numbers * 157 products , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-10-63f1276de8a3> in <module> ----> 1 numbers = make_array (42,4224,42422424,-250) 2 products = numbers * 157 3 products NameError: name 'make_array' is not defined Question 3. Oops, we made a typo! Instead of 157, we wanted to multiply each number by 1577. Compute the correct products in the cell below using array arithmetic. Notice that your job is really easy if you previously defined an array containing the 4 numbers. [11]: correct_products = numbers * 1577 correct_products 5
, --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-11-8ce201572911> in <module> ----> 1 correct_products = numbers * 1577 2 correct_products NameError: name 'numbers' is not defined Question 4. We’ve loaded an array of temperatures in the next cell. Each number is the highest temperature observed on a day at a climate observation station, mostly from the US. Since they’re from the US government agency NOAA , all the temperatures are in Fahrenheit. Convert them all to Celsius by first subtracting 32 from them, then multiplying the results by 5 9 . Make sure to ROUND the final result after converting to Celsius to the nearest integer using the np.round function. [12]: max_temperatures = Table . read_table( "temperatures.csv" ) . column( "Daily Max , Temperature" ) celsius_max_temperatures = np . round((max_temperatures) - 32 ) * 5/9 celsius_max_temperatures , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-12-8af64fb02f2f> in <module> ----> 1 max_temperatures = Table.read_table("temperatures.csv"). , column("Daily Max Temperature") 2 3 celsius_max_temperatures = np.round((max_temperatures) - 32) * 5/9 4 celsius_max_temperatures NameError: name 'Table' is not defined Question 5. The cell below loads all the lowest temperatures from each day (in Fahrenheit). Compute the size of the daily temperature range for each day. That is, compute the difference between each daily maximum temperature and the corresponding daily minimum temperature. 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
Pay attention to the units, give your answer in Celsius! Make sure NOT to round your answer for this question! [13]: min_temperatures = Table . read_table( "temperatures.csv" ) . column( "Daily Min , Temperature" ) celsius_temperature_ranges = ((max_temperatures) -32 ) * 5/9 - , ((min_temperatures) -32 ) * 5/9 celsius_temperature_ranges , --------------------------------------------------------------------------- NameError Traceback (most recent call , last) <ipython-input-13-c495c5d7b7e2> in <module> ----> 1 min_temperatures = Table.read_table("temperatures.csv"). , column("Daily Min Temperature") 2 3 celsius_temperature_ranges = ((max_temperatures)-32) * 5/9 - , ((min_temperatures)-32) * 5/9 4 celsius_temperature_ranges NameError: name 'Table' is not defined 1.4 4. World Population The cell below loads a table of estimates of the world population for different years, starting in 1950. The estimates come from the US Census Bureau website . [45]: world = Table . read_table( "world_population.csv" ) . select( 'Year' , 'Population' ) world . show( 4 ) The name population is assigned to an array of population estimates. [46]: population = world . column( 1 ) population In this question, you will apply some built-in Numpy functions to this array. Numpy is a module that is often used in Data Science! The difference function np.diff subtracts each element in an array from the element after it within the array. As a result, the length of the array np.diff returns will always be one less than the length of the input array. 7
The cumulative sum function np.cumsum outputs an array of partial sums. For example, the third element in the output array corresponds to the sum of the first, second, and third elements. Question 1. Very often in data science, we are interested understanding how values change with time. Use np.diff and np.max (or just max ) to calculate the largest annual change in population between any two consecutive years. [47]: largest_population_change = ... largest_population_change Question 2. What do the values in the resulting array represent (choose one)? [49]: np . cumsum(np . diff(population)) 1) The total population change between consecutive years, starting at 1951. 2) The total population change between 1950 and each later year, starting at 1951. 3) The total population change between 1950 and each later year, starting inclusively at 1950. [50]: # Assign cumulative_sum_answer to 1, 2, or 3 cumulative_sum_answer = ... 1.5 5. Old Faithful Old Faithful is a geyser in Yellowstone that erupts every 44 to 125 minutes (according to Wikipedia ). People are often told that the geyser erupts every hour , but in fact the waiting time between eruptions is more variable. Let’s take a look. Question 1. The first line below assigns waiting_times to an array of 272 consecutive waiting times between eruptions, taken from a classic 1938 dataset. Assign the names shortest , longest , and average so that the print statement is correct. [54]: waiting_times = Table . read_table( 'old_faithful.csv' ) . column( 'waiting' ) shortest = ... longest = ... average = ... print ( "Old Faithful erupts every" , shortest, "to" , longest, "minutes and , every" , average, "minutes on average." ) Question 2. Assign biggest_decrease to the biggest decrease in waiting time between two consecutive eruptions. For example, the third eruption occurred after 74 minutes and the fourth after 62 minutes, so the decrease in waiting time was 74 - 62 = 12 minutes. Hint 1 : You’ll need an array arithmetic function mentioned in the textbook . You have also seen this function earlier in the homework! Hint 2 : We want to return the absolute value of the biggest decrease. 8
[61]: biggest_decrease = ... biggest_decrease Question 3. If you expected Old Faithful to erupt every hour, you would expect to wait a total of 60 * k minutes to see k eruptions. Set difference_from_expected to an array with 272 elements, where the element at index i is the absolute difference between the expected and actual total amount of waiting time to see the first i+1 eruptions. Hint : You’ll need to compare a cumulative sum to a range. You’ll go through np.arange more thoroughly in Lab 3, but you can read about it in this textbook section . For example, since the first three waiting times are 79, 54, and 74, the total waiting time for 3 eruptions is 79 + 54 + 74 = 207. The expected waiting time for 3 eruptions is 60 * 3 = 180. Therefore, difference_from_expected.item(2) should be | 207 180 | = 27 . [65]: difference_from_expected = ... difference_from_expected Question 4. Let’s imagine your guess for the next wait time was always just the length of the previous waiting time. If you always guessed the previous waiting time, how big would your error in guessing the waiting times be, on average? For example, since the first three waiting times are 79, 54, and 74, the average difference between your guess and the actual time for just the second and third eruption would be | 79 54 | + | 54 74 | 2 = 22 . 5 . [68]: average_error = ... average_error 1.6 6. Tables Question 1. Suppose you have 4 apples, 3 oranges, and 3 pineapples. (Perhaps you’re using Python to solve a high school Algebra problem.) Create a table that contains this information. It should have two columns: fruit name and count . Assign the new table to the variable fruits . Note: Use lower-case and singular words for the name of each fruit, like "apple" . [71]: # Our solution uses 1 statement split over 3 lines. fruits = ... ... ... fruits Question 2. The file inventory.csv contains information about the inventory at a fruit stand. Each row represents the contents of one box of fruit. Load it as a table named inventory using the Table.read_table() function. Table.read_table(...) takes one argument (data file name in string format) and returns a table. [73]: inventory = ... inventory 9
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
Question 3. Does each box at the fruit stand contain a different fruit? Set all_different to True if each box contains a different fruit or to False if multiple boxes contain the same fruit. Hint: You don’t have to write code to calculate the True/False value for all_different . Just look at the inventory table and assign all_different to either True or False according to what you can see from the table in answering the question. [75]: all_different = ... all_different Question 4. The file sales.csv contains the number of fruit sold from each box last Saturday. It has an extra column called “price per fruit ($)” that’s the price per item of fruit for fruit in that box. The rows are in the same order as the inventory table. Load these data into a table called sales . [78]: sales = ... sales Question 5. How many fruits did the store sell in total on that day? [80]: total_fruits_sold = ... total_fruits_sold Question 6. What was the store’s total revenue (the total price of all fruits sold) on that day? Hint: If you’re stuck, think first about how you would compute the total revenue from just the grape sales. [83]: total_revenue = ... total_revenue Question 7. Make a new table called remaining_inventory . It should have the same rows and columns as inventory , except that the amount of fruit sold from each box should be subtracted from that box’s count, so that the “count” is the amount of fruit remaining after Saturday. [86]: remaining_inventory = ... ... ... ... remaining_inventory 10