lab2_dataTypes_new-2024

html

School

Temple University *

*We aren’t endorsed by this school

Course

1013

Subject

Computer Science

Date

Feb 20, 2024

Type

html

Pages

20

Uploaded by dayshaw03

Report
Lab 2: Data Types Welcome to Lab 2! Last time, we had our first look at Python and Jupyter notebooks. In this lab, we are going to look at a few different data types including numbers and text. A piece of text is called a string in Python. Last, you'll learn more about working with datasets in Python. First, initialize the grader. Each time you come back to this site to work on the lab, you will need to run this cell again. In [241]: from gofer.ok import check import os user = os.getenv('JUPYTERHUB_USER') In [242]: # Enter your name as a string # Example dogname = "Phineas" # Your name name = "Daysha Williams" 1. Data Types and Variables Variables (names) are central to coding in any programming language and can store numbers, strings such as "Hello World" , and even whole data sets. It is important that we understand the concept of data type because in coding the functions that we can use to alter the values stored in variables depend on the data type. In [243]: number = 6.75 The type function in Python has a variable name as the argument and returns the data type In [244]: type(number) Out[244]: float The variable, number contains a value with a datatype of float meaning floating point number. A float can be converted to an integer with the int Python function. In [245]: int(number) Out[245]: 6 In [246]: inumber = int(number) Below determine the type of inumber In [247]: type(inumber) Out[247]: int A string is another data type, test this out by checking the type of dogname defined above. In [248]: type(dogname) Out[248]:
str 2.1 Application: A physics experiment On the Apollo 15 mission to the Moon, astronaut David Scott famously replicated Galileo's physics experiment in which he showed that gravity accelerates objects of different mass at the same rate. Because there is no air resistance for a falling object on the surface of the Moon, even two objects with very different masses and densities should fall at the same rate. David Scott compared a feather and a hammer. You can run the following cell to watch a video of the experiment. In [249]: from IPython.display import YouTubeVideo # The original URL is: # https://www.youtube.com/watch?v=U7db6ZeLR5s YouTubeVideo("U7db6ZeLR5s") Out[249]: Object 1 Here's the transcript of the video: 167:22:06 Scott : Well, in my left hand, I have a feather; in my right hand, a hammer. And I guess one of the reasons we got here today was because of a gentleman named Galileo, a long time ago, who made a rather significant discovery about falling objects in gravity fields. And we thought where would be a better place to confirm his findings than on the Moon. And so we thought we'd try it here for you. The feather happens to be, appropriately, a falcon feather for our Falcon. And I'll drop the two of them here and, hopefully, they'll hit the ground at the same time. 167:22:43 Scott : How about that! 167:22:45 Allen : How about that! (Applause in Houston) 167:22:46 Scott : Which proves that Mr. Galileo was correct in his findings. Newton's Law. Using this footage, we can also attempt to confirm another famous bit of physics: Newton's law of universal gravitation. Newton's laws predict that any object dropped near the surface of the Moon should fall $$\frac{1}{2} G \frac{M}{R^2} t^2 \text{ meters}$$ after $t$ seconds, where $G$ is a universal constant, $M$ is the moon's mass in kilograms, and $R$ is the moon's radius in meters. So if we know $G$, $M$, and $R$, then Newton's laws let us predict how far an object will fall over any amount of time. To verify the accuracy of this law, we will calculate the difference between the predicted
distance the hammer drops and the actual distance. (If they are different, it might be because Newton's laws are wrong, or because our measurements are imprecise, or because there are other factors affecting the hammer for which we haven't accounted.) Someone studied the video and estimated that the hammer was dropped 113 cm from the surface. Counting frames in the video, the hammer falls for 1.2 seconds (36 frames). Question 1. Complete the code in the next cell to fill in the data from the experiment. In [250]: # t, the duration of the fall in the experiment, in seconds, based on the video. # Fill this in. time = 1.2 # The estimated distance the hammer actually fell, in meters, again based on the video. # Fill this in. estimated_distance_m = 1.13 In [251]: check('tests/q1.py') Out[251]: All tests passed! Question 2. Now, complete the code in the next cell to compute the difference between the predicted and estimated distances (in meters) that the hammer fell in this experiment. This just means translating the formula above ($\frac{1}{2}G\frac{M}{R^2}t^2$) into Python code. You'll have to replace each variable in the math formula with the name we gave that number in Python code. In [252]: # First, we've written down the values of the 3 universal # constants that show up in Newton's formula. # G, the universal constant measuring the strength of gravity. gravity_constant = 6.674 * 10**-11 # M, the moon's mass, in kilograms. moon_mass_kg = 7.34767309 * 10**22 # R, the radius of the moon, in meters. moon_radius_m = 1.737 * 10**6 # The distance the hammer should have fallen over the # duration of the fall, in meters, according to Newton's # law of gravity. The text above describes the formula # for this distance given by Newton's law. # **YOU FILL THIS PART IN.** predicted_distance_m = 1.17022 # Here we've computed the difference between the predicted # fall distance and the distance we actually measured. # If you've filled in the above code, this should just work. difference = predicted_distance_m - estimated_distance_m difference
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
Out[252]: 0.040220000000000145 In [253]: check('tests/q2.py') Out[253]: All tests passed! 3. Text Programming doesn't just concern numbers. Text is one of the most common types of values used in programs. A snippet of text is represented by a string value in Python. The word " string " is a programming term for a sequence of characters. A string might contain a single character, a word, a sentence, or a whole book. To distinguish text data from actual code, we demarcate strings by putting quotation marks around them. Single quotes ( ' ) and double quotes ( " ) are both valid, but the types of opening and closing quotation marks must match. The contents can be any sequence of characters, including numbers and symbols. Just like names can be given to numbers, names can be given to string values. The names and strings aren't required to be similar in any way. Any name can be assigned to any string. In [254]: one = 'two' plus = '*' print(one, plus, one) two * two Question 3. Yuri Gagarin was the first person to travel through outer space. When he emerged from his capsule upon landing on Earth, he reportedly had the following conversation with a woman and girl who saw the landing: The woman asked: "Can it be that you have come from outer space?" Gagarin replied: "As a matter of fact, I have!" The cell below contains unfinished code. Fill in the ... s so that it prints out this conversation exactly as it appears above. In [255]: woman_asking = 'The woman asked:' woman_quote = '"Can it be that you have come from outer space?"' gagarin_reply = 'Gagarin replied:' gagarin_quote = '"As a matter of fact, I have!"' print(woman_asking, woman_quote) print(gagarin_reply, gagarin_quote) The woman asked: "Can it be that you have come from outer space?" Gagarin replied: "As a matter of fact, I have!" In [256]: check('tests/q3.py') Out[256]: All tests passed! 4. Calling functions The most common way to combine or manipulate values in Python is by calling functions. Python comes with many built-in functions that perform common operations.
For example, the abs function takes a single number as its argument and returns the absolute value of that number. The absolute value of a number is its distance from 0 on the number line, so abs(5) is 5 and abs(-5) is also 5. 4.1. Application: Computing walking distances Chunhua is on the corner of 7th Avenue and 42nd Street in Midtown Manhattan, and she wants to know far she'd have to walk to get to Gramercy School on the corner of 10th Avenue and 34th Street. She can't cut across blocks diagonally, since there are buildings in the way. She has to walk along the sidewalks. Using the map below, she sees she'd have to walk 3 avenues (long blocks) and 8 streets (short blocks). In terms of the given numbers, she computed 3 as the difference between 7 and 10, in absolute value , and 8 similarly. Chunhua also knows that blocks in Manhattan are all about 80m by 274m (avenues are farther apart than streets). So in total, she'd have to walk $(80 \times |42 - 34| + 274 \ times |7 - 10|)$ meters to get to the park. Question 4. Finish the line num_avenues_away = ... in the next cell so that the cell calculates the distance Chunhua must walk and gives it the name manhattan_distance . Everything else has been filled in for you. Use the abs function. In [257]: # Here's the number of streets away: num_streets_away = abs(42-34) # Compute the number of avenues away in a similar way: num_avenues_away = abs(7-10) street_length_m = 80 avenue_length_m = 274 # Now we compute the total distance Chunhua must walk. manhattan_distance = street_length_m*num_streets_away + avenue_length_m*num_avenues_away # We've included this line so that you see the distance # you've computed when you run this cell. You don't need # to change it, but you can if you want. manhattan_distance Out[257]: 1462 Be sure to run the next cell to test your code. In [258]: check('tests/q4.py') Out[258]: All tests passed! Multiple arguments Some functions take multiple arguments, separated by commas. For example, the built- in max function returns the maximum argument passed to it. In [259]: max(2, -3, 4, -5) Out[259]:
4 4.2 Understanding nested expressions Function calls and arithmetic expressions can themselves contain expressions. You saw an example in the last question: abs(42-34) has two number expressions in a subtraction expression in a function call expression. And you probably wrote something like abs(7-10) to compute num_avenues_away . Nested expressions can turn into complicated-looking code. However, the way in which complicated expressions break down is very regular. Question 5. Given the heights of the Splash Triplets from the Golden State Warriors, write an expression that computes the smallest difference between any of the three heights. Your expression shouldn't have any numbers in it, only function calls and the names klay , steph , and kevin . Give the value of your expression the name min_height_difference . In [260]: # The three players' heights, in meters: klay = 2.01 # Klay Thompson is 6'7" steph = 1.91 # Steph Curry is 6'3" kevin = 2.06 # Kevin Durant is officially 6'9", but many suspect that he is taller. # (Further complicating matters, membership of the "Splash Triplets" # is disputed, since it was originally used in reference to # Klay Thompson, Steph Curry, and Draymond Green.) We'd like to look at all three pairs of heights, compute the absolute difference between each pair, and then find the smallest of those three absolute differences. This is left to you! If you're stuck, try computing the value for each step of the process (like the difference between Klay's heigh and Steph's height) on a separate line and giving it a name (like klay_steph_height_diff). You can add as many lines of code as you like. In [261]: klay_steph_height_diff = ... min_height_difference = (0.05) In [262]: check('tests/q5.py') Out[262]: All tests passed! 4.3 String Methods Strings can be transformed using methods , which are functions that involve an existing string and some other arguments. One example is the replace method, which replaces all instances of some part of a string with some alternative. A method is invoked on a string by placing a . after the string value, then the name of the method, and finally parentheses containing the arguments. Here's a sketch, where the < and > symbols aren't part of the syntax; they just mark the boundaries of sub- expressions. <expression that evaluates to a string>.<method name>(<argument>, <argument>, ...) Try to predict the output of these examples, then execute them. In [263]: 'hitchhiker'.replace('hi', 'ma') Out[263]:
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
'matchmaker' In [264]: # Replace a sequence of letters, which appears twice 'hitchhiker'.replace('hi', 'ma') Out[264]: 'matchmaker' Once a name is bound to a string value, methods can be invoked on that name as well. The name is still bound to the original string, so a new name is needed to capture the result. In [265]: sharp = 'edged' hot = sharp.replace('ed', 'ma') print('sharp:', sharp) print('hot:', hot) sharp: edged hot: magma Just like we can nest functions together such as what you did in question 5, you can also invoke a method on the output of another method call, this is also sometimes called 'chained' methods. In [266]: # Calling replace on the output of another call to replace 'train'.replace('t', 'ing').replace('in', 'de') Out[266]: 'degrade' Here's a picture of how Python evaluates a "chained" method call like that: Question 6. Data cleaning: Imagine you have a data set with nitrogen gas volumes at a range of temperatures in Kelvin. You would like to get the data ready for plotting and further analysis but there is a problem! The data contains labels along with the numbers for volume in liters (L) and temperature in Kelvin (K). By using replace we can replace each label with an empty string to remove the label. Further down in Question 9 we will convert each value to different units. In [267]: gasdata = '300K, 24.6171L' gasdata Out[267]: '300K, 24.6171L' In [268]: gasdata = gasdata.replace('K','') print(gasdata) gasdata = gasdata.replace('L','') print(gasdata) 300, 24.6171L 300, 24.6171 In [269]: check('tests/q6new.py') Out[269]:
All tests passed! Other string methods do not take any arguments at all, because the original string is all that's needed to compute the result. In these cases, parentheses are still needed, but there's nothing in between the parentheses. Here are some methods that take no arguments: Method name Value lower a lowercased version of the string upper an uppercased version of the string capitalize a version with the first letter capitalized title a version with the first letter of every word capitalized All these string methods are useful, but most programmers don't memorize their names or how to use them. Instead, people usually just search the internet for documentation and examples. A complete list of string methods appears in the Python language documentation. Stack Overflow has a huge database of answered questions that often demonstrate how to use these methods to achieve various ends. 4.3.1 Strings as function arguments String values, like numbers, can be arguments to functions and can be returned by functions. The function len takes a single string as its argument and returns the number of characters in the string: its len gth. Note that it doesn't count words . len("one small step for man") is 22, not 5. Let's try using len. In [270]: our_school = 'Temple Univerisity' len(our_school) Out[270]: 18 Question 7. Periodically, you will be asked questions like this one that require a written response. There is no check to run on the answer, but your answers to written questions are graded, so be sure to answer them! In the example about, the len function counted the space between between the two words as a character. Why do you think it did so? Does this make sense to you? Answer in the markdown cell below. Question 8. Use len to find out the number of characters in the very long string in the next cell. (It's the first sentence of the English translation of the French Declaration of the Rights of Man .) The length of a string is the total number of characters in it, including things like spaces and punctuation. Assign sentence_length to that number. In [271]: a_very_long_sentence = "The representatives of the French people, organized as a National Assembly, believing that the ignorance, neglect, or contempt of the rights of man are the sole cause of public calamities and of the corruption of governments, have determined to set forth in a solemn declaration the natural, unalienable, and sacred rights of man, in order that this declaration, being constantly before all the members of the Social body, shall remind them continually of their rights and duties; in order that the acts of the
legislative power, as well as those of the executive power, may be compared at any moment with the objects and purposes of all political institutions and may thus be more respected, and, lastly, in order that the grievances of the citizens, based hereafter upon simple and incontestable principles, shall tend to the maintenance of the constitution and redound to the happiness of all." sentence_length = 896 sentence_length Out[271]: 896 In [272]: check('tests/q8.py') Out[272]: All tests passed! 4.3.2 Converting to and from Strings Strings and numbers are different types of values, even when a string contains the digits of a number. For example, evaluating the following cell causes an error because an integer cannot be added to a string. In [273]: 8 + "8" --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[273], line 1 ----> 1 8 + "8" TypeError: unsupported operand type(s) for +: 'int' and 'str' However, there are built-in functions to convert numbers to strings and strings to numbers. Function name Effect Example int Converts a string of digits and perhaps a negative sign to an integer ( int ) value int("42") float Converts a string of digits and perhaps a negative sign and decimal point to a decimal ( float ) value float("4.2") str Converts any value to a string ( str ) value str(42) eval A string is evaluated as Python code. Example convert Celsius to Fahrenheit eval("25*9/5+ 32") What do you think the following cell will evaluate to? In [ ]: 8 + int("8") Here is an example of using eval to convert kilogram (kg) to gram (g) (run these cells to explore): In [ ]: mass_string = '1.50kg' eval(mass_string.replace('kg','*1000'))
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
In [ ]: str(eval(mass_string.replace('kg','*1000')))+'g' Question 9. Use replace and eval together to convert our gas data so that volumes are numbers in milliliter (mL) and temperatures are in Celsius (C). Do not to use any numbers other than conversion factors in your solution, but instead manipulate the strings that are provided. In [ ]: gasdata = '300K, 24.6171L' gasdata In [ ]: gasdata_convert=gasdata.replace('K','-273.15') gasdata_convert=gasdata_convert.replace('L','+24592.4829') gasdata_convert In [ ]: gasdata_convert = eval(gasdata_convert) gasdata_convert # gasdata_convert is actually now a tuple another type of Python sequence In [ ]: print('The original gas data is', gasdata, 'and now after converting volume to mL and temperature to Celsius is ', gasdata_convert) In [ ]: check('tests/q9new.py') 4.4 Importing code What has been will be again, what has been done will be done again; there is nothing new under the sun. Most programming involves work that is very similar to work that has been done before. Since writing code is time consuming, it's good to rely on others' published code when you can. Rather than copy-pasting, Python allows us to import other code, creating a module that contains all of the names created by that code. Python includes many useful modules that are just an import away. We'll look at the math module as a first example. The math module is extremely useful in computing mathematical expressions in Python. Suppose we want to very accurately compute the area of a circle with radius 5 meters. For that, we need the constant $\pi$, which is roughly 3.14. Conveniently, the math module has pi defined for us: In [ ]: import math radius = 5 area_of_circle = radius**2 * math.pi area_of_circle pi is defined inside math , and the way that we access names that are inside modules is by writing the module's name, then a dot, then the name of the thing we want: <module name>.<name> In order to use a module at all, we must first write the statement import <module name> . That statement creates a module object with things like pi in it and then assigns the name math to that module. Above we have done that for math . Modules can provide other named things, including functions . For example, math provides the name sin for the sine function. Having imported math already, we can write math.sin(3) to compute the sine of 3. (Note that this sine function considers its
argument to be in radians , not degrees. 180 degrees are equivalent to $\pi$ radians.) Question 10. A $\frac{\pi}{4}$-radian (45-degree) angle forms a right triangle with equal base and height, pictured below. If the hypotenuse (the radius of the circle in the picture) is 1, then the height is $\sin(\frac{\pi}{4})$. Compute that using sin and pi from the math module. Give the result the name sine_of_pi_over_four . (Source: [Wolfram MathWorld](http://mathworld.wolfram.com/images/eps-gif/TrigonometryAnglesPi4_1000. gif)) In [276]: sine_of_pi_over_four = round(math.sin(math.pi/4),8) sine_of_pi_over_four Out[276]: 0.70710678 In [277]: check('tests/q10.py') Out[277]: All tests passed! For your reference, here are some more examples of functions from the math module. Note how different methods take in different number of arguments. Often, the documentation of the module will provide information on how many arguments is required for each method. In [278]: # Calculating factorials. math.factorial(5) Out[278]: 120 In [279]: # Calculating logarithms (the logarithm of 8 in base 2). # The result is 3 because 2 to the power of 3 is 8. math.log(8, 2) Out[279]: 3.0 There are many variations of how we can import methods from outside sources. For example, we can import just a specific method from an outside source, we can rename a library we import, and we can import every single method from a whole library. In [280]: # Importing just cos and pi from math.
# Now, we don't have to use "math." before these names. from math import cos, pi print(cos(pi)) -1.0 In [281]: # We can nickname math as something else, if we don't want to type the name math import math as m m.log(m.pi) Out[281]: 1.1447298858494002 In [282]: # Lastly, we can import ever thing from math and use all of its names without "math." from math import * log(pi) Out[282]: 1.1447298858494002 Question 11. This last approach of importing all the names within a module without the module name is generally not recommended. Suppose you were calculating the dimensions of your appartment and you create a variable named 'floor' to store the result when you calculate the number of square feet. Well, the math module includes a function named 'floor' that rounds numbers down to the nearest integer (i.g., floor(4.2) is 4). What do you think would happen if you type: from math import * after you have already created a variable named floor? How does just typing import math avoid this problem? Answer in the markdown cell below. 5. Lists and Arrays 5.1 Lists Lists are a way Python can store multiple pieces of data. For instance the abbreviated days of the week: In [283]: ['M','T','W','R','F','S','S'] Out[283]: ['M', 'T', 'W', 'R', 'F', 'S', 'S'] We can make lists of numbers and even draw on our imported math module to add some interesting numbers. In [284]: [math.pi,0,-1,math.e] Out[284]: [3.141592653589793, 0, -1, 2.718281828459045] Operations or functions can be performed on members of a list using a powerful technique know as list comprehension, study these examples: In [285]: list = [0, 1, 2, 3, 4] list Out[285]: [0, 1, 2, 3, 4] In [286]: [2*x for x in list]
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
Out[286]: [0, 2, 4, 6, 8] In [287]: [2**x for x in list] Out[287]: [1, 2, 4, 8, 16] Question 12a. The list below contains the height in meters of the 4 tallest mountains in the Adirondack Mountains ( see Highpeaks ). Use list comprehension to convert these heights (elevation) to feet. In [288]: ADK_highpeaks = [1629,1559,1512,1501] ADK_highpeaks Out[288]: [1629, 1559, 1512, 1501] In [289]: m_to_ft = 3.28084 # Find and place the conversion from meters to feet here In [290]: ADK_highpeaks_ft = [3.28084*x for x in ADK_highpeaks] In [291]: check('tests/q12new.py') Out[291]: All tests passed! 5.2 Arrays Up to now, we haven't done much that you couldn't do yourself by hand, without going through the trouble of learning Python. Computers are most useful when a small amount of code performs a lot of work by performing the same action to many different things . For example, in the time it takes you to calculate the 18% tip on a restaurant bill, a laptop can calculate 18% tips for every restaurant bill paid by every human on Earth that day. (That's if you're pretty fast at doing arithmetic in your head!) Arrays are how we put many values in one place so that we can operate on them as a group. For example, if billions_of_numbers is an array of numbers, the expression .18 * billions_of_numbers gives a new array of numbers that's the result of multiplying each number in billions_of_numbers by .18 (18%). Arrays are not limited to numbers; we can also put all the words in a book into an array of strings. Concretely, an array is a collection of values of the same type , like a column in an Excel spreadsheet. 5.1. Making arrays You can type in the data that goes in an array yourself, but that's not typically how programs work. Normally, we create arrays by loading them from an external source, like a data file. First, though, let's learn how to start from scratch. Execute the following cell so that all the names from the datascience module are available to you. The documentation for this module is available at http://data8.org/datascience . In [292]:
from datascience import * Wait a minute! Didn't we do what we cautioned against in question 11 by importing * from a module? Yes, we did. However, the datascience module is not vary large. It does not define very many new names, so the liklihood of overwriting a variable we defined previously is small. It is certainly more convenient to type make_array() rather than datascience.make_array() For that reason, you will see that we include "from datascience import *" at the top of all of the problemset notebooks. Now, to create an array, call the function make_array . Each argument you pass to make_array will be in the array it returns. Run this cell to see an example: In [293]: make_array(0.125, 4.75, -1.3) Out[293]: array([ 0.125, 4.75 , -1.3 ]) Each value in an array (in the above case, the numbers 0.125, 4.75, and -1.3) is called an element or item of that array. Arrays themselves are also values, just like numbers and strings. That means you can assign them names or use them as arguments to functions. Question 12b. Make an array containing the numbers 0, 1, -1, $\pi$, and $e$, in that order. Name it interesting_numbers . Hint: How did you get the values $\pi$ and $e$ earlier? You can refer to them in exactly the same way here. In [294]: interesting_numbers = make_array (0, 1, -1, math.pi, math.e) interesting_numbers Out[294]: array([ 0. , 1. , -1. , 3.14159265, 2.71828183]) In [295]: check('tests/q12.py') Out[295]: All tests passed! 5.2. np.arange Arrays are provided by a package called NumPy (pronounced "NUM-pie" or, if you prefer to pronounce things incorrectly, "NUM-pee"). The package is called numpy , but it's standard to rename it np for brevity. You can do that with: import numpy as np Very often in data science, we want to work with many numbers that are evenly spaced within some range. NumPy provides a special function for this called arange . np.arange(start, stop, space) produces an array with all the numbers starting at start and counting up by space , stopping before stop is reached. For example, the value of np.arange(1, 6, 2) is an array with elements 1, 3, and 5 -- it starts at 1 and counts up by 2, then stops before 6. In other words, it's equivalent to make_array(1, 3, 5) . np.arange(4, 9, 1) is an array with elements 4, 5, 6, 7, and 8. (It doesn't contain 9 because np.arange stops before the stop value is reached.) Execute the below cell to see how to make an array of the first 10 integers. In [296]:
import numpy as np first_array = np.arange(1,11) first_array Out[296]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) Now create your own array with the 6 possible outcomes on a six sided die In [297]: six_sided = np.arange (0,7) six_sided Out[297]: array([0, 1, 2, 3, 4, 5, 6]) Question 13. Import numpy as np and then use np.arange to create an array with the multiples of 99 from 0 up to ( and including ) 9999. (So its elements are 0, 99, 198, 297, etc.) In [298]: import numpy as np multiples_of_99 = np.arange(0,10000,99) multiples_of_99 Out[298]: array([ 0, 99, 198, 297, 396, 495, 594, 693, 792, 891, 990, 1089, 1188, 1287, 1386, 1485, 1584, 1683, 1782, 1881, 1980, 2079, 2178, 2277, 2376, 2475, 2574, 2673, 2772, 2871, 2970, 3069, 3168, 3267, 3366, 3465, 3564, 3663, 3762, 3861, 3960, 4059, 4158, 4257, 4356, 4455, 4554, 4653, 4752, 4851, 4950, 5049, 5148, 5247, 5346, 5445, 5544, 5643, 5742, 5841, 5940, 6039, 6138, 6237, 6336, 6435, 6534, 6633, 6732, 6831, 6930, 7029, 7128, 7227, 7326, 7425, 7524, 7623, 7722, 7821, 7920, 8019, 8118, 8217, 8316, 8415, 8514, 8613, 8712, 8811, 8910, 9009, 9108, 9207, 9306, 9405, 9504, 9603, 9702, 9801, 9900, 9999]) In [299]: check('tests/q13.py') Out[299]: All tests passed! 5.3. Application: Temperature readings NOAA (the US National Oceanic and Atmospheric Administration) operates weather stations that measure surface temperatures at different sites around the United States. The hourly readings are publicly available . Suppose we download all the hourly data from the Oakland, California site for the month of December 2015. To analyze the data, we want to know when each reading was taken, but we find that the data don't include the timestamps of the readings (the time at which each one was taken). However, we know the first reading was taken at the first instant of December 2015 (midnight on December 1st) and each subsequent reading was taken exactly 1 hour after the last. Question 14. Create an array of the time, in seconds, since the start of the month at which each hourly reading was taken. Name it collection_times . Hint 1: There were 31 days in December, which is equivalent to ($31 \times 24$) hours or ($31 \times 24 \times 60 \times 60$) seconds. So your array should have $31 \times 24$ elements in it.
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
Hint 2: The len function works on arrays, too. If your collection_times isn't passing the tests, check its length and make sure it has $31 \times 24$ elements. In [300]: collection_times = np.arange(0,2678400,3600) collection_times Out[300]: array([ 0, 3600, 7200, 10800, 14400, 18000, 21600, 25200, 28800, 32400, 36000, 39600, 43200, 46800, 50400, 54000, 57600, 61200, 64800, 68400, 72000, 75600, 79200, 82800, 86400, 90000, 93600, 97200, 100800, 104400, 108000, 111600, 115200, 118800, 122400, 126000, 129600, 133200, 136800, 140400, 144000, 147600, 151200, 154800, 158400, 162000, 165600, 169200, 172800, 176400, 180000, 183600, 187200, 190800, 194400, 198000, 201600, 205200, 208800, 212400, 216000, 219600, 223200, 226800, 230400, 234000, 237600, 241200, 244800, 248400, 252000, 255600, 259200, 262800, 266400, 270000, 273600, 277200, 280800, 284400, 288000, 291600, 295200, 298800, 302400, 306000, 309600, 313200, 316800, 320400, 324000, 327600, 331200, 334800, 338400, 342000, 345600, 349200, 352800, 356400, 360000, 363600, 367200, 370800, 374400, 378000, 381600, 385200, 388800, 392400, 396000, 399600, 403200, 406800, 410400, 414000, 417600, 421200, 424800, 428400, 432000, 435600, 439200, 442800, 446400, 450000, 453600, 457200, 460800, 464400, 468000, 471600, 475200, 478800, 482400, 486000, 489600, 493200, 496800, 500400, 504000, 507600, 511200, 514800, 518400, 522000, 525600, 529200, 532800, 536400, 540000, 543600, 547200, 550800, 554400, 558000, 561600, 565200, 568800, 572400, 576000, 579600, 583200, 586800, 590400, 594000, 597600, 601200, 604800, 608400, 612000, 615600, 619200, 622800, 626400, 630000, 633600, 637200, 640800, 644400, 648000, 651600, 655200, 658800, 662400, 666000, 669600, 673200, 676800, 680400, 684000, 687600, 691200, 694800, 698400, 702000, 705600, 709200, 712800, 716400, 720000, 723600, 727200, 730800, 734400, 738000, 741600, 745200, 748800, 752400, 756000, 759600, 763200, 766800, 770400, 774000, 777600, 781200, 784800, 788400, 792000, 795600, 799200, 802800, 806400, 810000, 813600, 817200, 820800, 824400, 828000, 831600, 835200, 838800, 842400, 846000, 849600, 853200, 856800, 860400, 864000, 867600, 871200, 874800, 878400, 882000, 885600, 889200, 892800, 896400, 900000, 903600, 907200, 910800, 914400, 918000, 921600, 925200, 928800, 932400, 936000, 939600, 943200, 946800, 950400, 954000, 957600, 961200, 964800, 968400, 972000, 975600, 979200, 982800, 986400, 990000, 993600, 997200, 1000800, 1004400, 1008000, 1011600, 1015200, 1018800, 1022400, 1026000, 1029600, 1033200, 1036800, 1040400, 1044000, 1047600, 1051200, 1054800, 1058400, 1062000, 1065600, 1069200, 1072800, 1076400, 1080000, 1083600, 1087200, 1090800, 1094400, 1098000, 1101600, 1105200, 1108800, 1112400, 1116000, 1119600, 1123200, 1126800, 1130400,
1134000, 1137600, 1141200, 1144800, 1148400, 1152000, 1155600, 1159200, 1162800, 1166400, 1170000, 1173600, 1177200, 1180800, 1184400, 1188000, 1191600, 1195200, 1198800, 1202400, 1206000, 1209600, 1213200, 1216800, 1220400, 1224000, 1227600, 1231200, 1234800, 1238400, 1242000, 1245600, 1249200, 1252800, 1256400, 1260000, 1263600, 1267200, 1270800, 1274400, 1278000, 1281600, 1285200, 1288800, 1292400, 1296000, 1299600, 1303200, 1306800, 1310400, 1314000, 1317600, 1321200, 1324800, 1328400, 1332000, 1335600, 1339200, 1342800, 1346400, 1350000, 1353600, 1357200, 1360800, 1364400, 1368000, 1371600, 1375200, 1378800, 1382400, 1386000, 1389600, 1393200, 1396800, 1400400, 1404000, 1407600, 1411200, 1414800, 1418400, 1422000, 1425600, 1429200, 1432800, 1436400, 1440000, 1443600, 1447200, 1450800, 1454400, 1458000, 1461600, 1465200, 1468800, 1472400, 1476000, 1479600, 1483200, 1486800, 1490400, 1494000, 1497600, 1501200, 1504800, 1508400, 1512000, 1515600, 1519200, 1522800, 1526400, 1530000, 1533600, 1537200, 1540800, 1544400, 1548000, 1551600, 1555200, 1558800, 1562400, 1566000, 1569600, 1573200, 1576800, 1580400, 1584000, 1587600, 1591200, 1594800, 1598400, 1602000, 1605600, 1609200, 1612800, 1616400, 1620000, 1623600, 1627200, 1630800, 1634400, 1638000, 1641600, 1645200, 1648800, 1652400, 1656000, 1659600, 1663200, 1666800, 1670400, 1674000, 1677600, 1681200, 1684800, 1688400, 1692000, 1695600, 1699200, 1702800, 1706400, 1710000, 1713600, 1717200, 1720800, 1724400, 1728000, 1731600, 1735200, 1738800, 1742400, 1746000, 1749600, 1753200, 1756800, 1760400, 1764000, 1767600, 1771200, 1774800, 1778400, 1782000, 1785600, 1789200, 1792800, 1796400, 1800000, 1803600, 1807200, 1810800, 1814400, 1818000, 1821600, 1825200, 1828800, 1832400, 1836000, 1839600, 1843200, 1846800, 1850400, 1854000, 1857600, 1861200, 1864800, 1868400, 1872000, 1875600, 1879200, 1882800, 1886400, 1890000, 1893600, 1897200, 1900800, 1904400, 1908000, 1911600, 1915200, 1918800, 1922400, 1926000, 1929600, 1933200, 1936800, 1940400, 1944000, 1947600, 1951200, 1954800, 1958400, 1962000, 1965600, 1969200, 1972800, 1976400, 1980000, 1983600, 1987200, 1990800, 1994400, 1998000, 2001600, 2005200, 2008800, 2012400, 2016000, 2019600, 2023200, 2026800, 2030400, 2034000, 2037600, 2041200, 2044800, 2048400, 2052000, 2055600, 2059200, 2062800, 2066400, 2070000, 2073600, 2077200, 2080800, 2084400, 2088000, 2091600, 2095200, 2098800, 2102400, 2106000, 2109600, 2113200, 2116800, 2120400, 2124000, 2127600, 2131200, 2134800, 2138400, 2142000, 2145600, 2149200, 2152800, 2156400, 2160000, 2163600, 2167200, 2170800, 2174400, 2178000, 2181600, 2185200, 2188800, 2192400, 2196000, 2199600, 2203200, 2206800, 2210400, 2214000, 2217600, 2221200, 2224800, 2228400, 2232000, 2235600, 2239200, 2242800, 2246400, 2250000, 2253600, 2257200, 2260800, 2264400, 2268000, 2271600, 2275200, 2278800, 2282400, 2286000, 2289600, 2293200, 2296800, 2300400, 2304000, 2307600, 2311200, 2314800, 2318400, 2322000, 2325600, 2329200, 2332800, 2336400, 2340000, 2343600, 2347200, 2350800, 2354400, 2358000, 2361600, 2365200, 2368800, 2372400, 2376000, 2379600, 2383200, 2386800, 2390400, 2394000, 2397600, 2401200, 2404800, 2408400, 2412000, 2415600,
2419200, 2422800, 2426400, 2430000, 2433600, 2437200, 2440800, 2444400, 2448000, 2451600, 2455200, 2458800, 2462400, 2466000, 2469600, 2473200, 2476800, 2480400, 2484000, 2487600, 2491200, 2494800, 2498400, 2502000, 2505600, 2509200, 2512800, 2516400, 2520000, 2523600, 2527200, 2530800, 2534400, 2538000, 2541600, 2545200, 2548800, 2552400, 2556000, 2559600, 2563200, 2566800, 2570400, 2574000, 2577600, 2581200, 2584800, 2588400, 2592000, 2595600, 2599200, 2602800, 2606400, 2610000, 2613600, 2617200, 2620800, 2624400, 2628000, 2631600, 2635200, 2638800, 2642400, 2646000, 2649600, 2653200, 2656800, 2660400, 2664000, 2667600, 2671200, 2674800]) In [301]: check('tests/q14.py') Out[301]: All tests passed! Question 15. The powers of 2 ($2^0 = 1$, $2^1 = 2$, $2^2 = 4$, etc) arise frequently in computer science. (For example, you may have noticed that storage on smartphones or USBs come in powers of 2, like 16 GB, 32 GB, or 64 GB.) Use np.arange and the exponentiation operator ** to compute the first 15 powers of 2, starting from 2^0 . In [302]: powers_of_2 = 2**np.arange(0,15,1) powers_of_2 Out[302]: array([ 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384]) In [303]: check('tests/q15.py') Out[303]: All tests passed! 6. Success! Congratulations, you're done with lab 2! Be sure to run all the tests and verify that they all pass (the next cell needs to be executed), and that you have answered any questions requiring a written response. Save and Export as, HTML from the File menu, Right click on file name to download noteook Upload and Submit your files to Canvas under the corresponding assignment . Question 16. At the end of each lab, please include a reflection. How did this lab go? Did you find the powers of 2 question tricky? Were there questions you found especially challenging you would like your instructor to review in class? How long did the lab take you to complete? Share your feedback so we can continue to improve this class! Insert a markdown cell below this one and write your reflection on this lab. In [304]: This lab went decent, I think I am getting a hang of everything. Yes I found the powers of 2 question tricky and had to do multiple runs in the cell
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
I would like the instructor to go over the power of 2s question for sure this lab took me 1 hour to complete Cell In[304], line 3 I would like the instructor to go over the power of 2s question for sure ^ SyntaxError: invalid decimal literal In [305]: import glob from gofer.ok import check for x in ['1', '2', '3', '4', '5', '6new', '8', '9new', '10', '12new', '12', '13', '14', '15']: print('Testing question {}: '.format(x)) display(check('tests/q{}.py'.format(x))) Testing question 1: All tests passed! Testing question 2: All tests passed! Testing question 3: All tests passed! Testing question 4: All tests passed! Testing question 5: All tests passed! Testing question 6new: All tests passed! Testing question 8: All tests passed! Testing question 9new: All tests passed! Testing question 10: All tests passed! Testing question 12new: All tests passed! Testing question 12: All tests passed! Testing question 13: All tests passed! Testing question 14: All tests passed! Testing question 15: All tests passed! In [306]: print("Nice work ",name, user) import time; localtime = time.asctime( time.localtime(time.time()) ) print("Submitted @ ", localtime) Nice work Daysha Williams tuo68512@temple.edu Submitted @ Wed Jan 31 04:07:26 2024 In [ ]: In [ ]:
In [ ]: In [ ]: