'XNH8QLYHUVLW\ (GPXQG73UDWW-U6FKRRORI(QJLQHHULQJ EGR 103L Fall 2017 Skills Quiz - Python Edition Solutions Michael R. Gustafson II Name (please print): NetID (please print): In keeping with the Community Standard, I have neither provided nor received any assistance on this test. I understand if it is later determined that I gave or received assistance, I will be brought before the Undergraduate Conduct Board and, if found responsible for academic dishonesty or academic contempt, fail the class. I also understand that I am not allowed to speak to anyone except the instructor about any aspect of this test until the instructor announces it is allowed. I understand if it is later determined that I did speak to another person about the test before the instructor said it was allowed, I will be brought before the Undergraduate Conduct Board and, if found responsible for academic dishonesty or academic contempt, fail the class. Signature: Notes You will be turning in each problem in a separate pile. Most of these problems will require working on additional pieces of paper - Make sure that you do not put work for more than any one problem on any one piece of paper. For this test, you will be turning in four different sets of work. Again, Please do not work on multiple problems on the same sheet of paper. Also - please do not put work for one problem on the back of another problem. Be sure your name and NetID show up on every page of the test. If you are including work on extra sheets of paper, put your name and NetID on each and be sure to staple them to the appropriate problem. Problems without names will incur at least a 25% penalty for the problem. Work must be down in dark ink and on only one side of the page. This first page should have your name, NetID, and signature on it. It should be stapled on top of and turned in with your submission for Problem I. Every other pile should have your test page on top followed by any previously blank paper used for that problem. You will not need and can not use a calculator on this test. You will be asked to write several lines of code on this test. Make sure what you write is Python code and not mathematics. Be very careful with any symbols you use and carefully indent lines! You do not need to put the honor code statement in your codes. The honor code statement on this page and your NetID on each problem stands in for that. You may assume that the following have been run for any code you write: import math as m import numpy as np import matplotlib. pyplot as plt If you specifically want to import things in a different way, you need to show that explicitly on each code.
Name (please print): Community Standard (print NetID): Problem I: [30 pts.] The Basics - NOT IN PYTHON YET!!! See CS 101 tests, specifically first problems, for similar code.
Name (please print): Community Standard (print NetID): Problem II: [24 pts.] Smart Home A home automation system collects temperature and humidity information every ten minutes and saves the readings each day to a text file. The file from yesterday is called Data01102017.dat and has five columns of information: the reading number, the hour the reading was taken (between 0 and 23), the minute of the hour the reading was taken (between 0 and 50), the temperature in Fahrenheit (the sensor can read between 40 and 110 degrees) and the relative humidity (reported as a percentage between 0 and 100). The start and end of the data table might resemble: 1 0 0 6.82e+01 5.23e+01 2 0 10 6.83e+01 5.21e+01 3 0 20 6.85e+01 5.25e+01 <etc> 142 23 30 6.27e+01 5.51e+01 143 23 40 6.26e+01 5.52e+01 144 23 50 6.23e+01 5.49e+01 but there are actually a total of 144 lines. (1) Load the data set into an array called home_info. (2) Copy the reading hours into an array called hours. (3) Copy the reading minutes into an array called minutes. (4) Copy the temperatures into an array called temps. (5) Copy the humidity readings into an array called hum. (6) Make a plot of the temperatures at the top of each hour (that is, when the minute value is 0) as a function of the hour using blue circles at each reading. The circles should not be connected to each other. Add a proper title, axis labels, and grid. Save this plot to a color Encapsulated Postscript file called temp_plot.eps. (7) Determine the lowest, average, and highest values of the temperatures and the lowest, average, and highest values of the humidity and print them out as follows: Measurement Low Average High Temperature: 6.23e+01 7.04e+01 7.30e+01 Humidity: 5.02e+01 5.34e+01 5.60e+01 where the represents a space. In your code for this part, you should use or spaces. or some other symbol to clearly indicate
1 # %% Imports (not required in solution) 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 # %% (1) 6 home_info = np.loadtxt( ³Data01102017.dat ³) 7 8 # %% (2) - (5) 9 hours = home_info[:, 1].copy() 10 minutes = home_info[:, 2].copy() 11 temps = home_info[:, 3].copy() 12 hum = home_info[:, 4].copy() 13 14 # %% (6) 15 plt.plot(hours[0::6], temps[0::6], ³bo ³) 16 plt.title( ³Temperature vs. Time ³) 17 plt.xlabel( ³Time, Hr ³) 18 plt.ylabel( ³Temp, ^o F ³) 19 plt.grid(1) 20 plt.savefig( ³temp_plot.eps ³) 21 22 # %% (7) 23 print( ³Measurement Low Average High ³) 24 print( ³Temperature:_{:8.2e}_{:9.2e}_{:9.2e} ³.format( 25 np.min(temps), np.mean(temps), np.max(temps))) 26 print( ³ Humidity:_{:8.2e}_{:9.2e}_{:9.2e} ³.format( 27 np.min(hum), np.mean(hum), np.max(hum))) 28 29 # Note: if spaces are included correctly, {:0.2e} through {:8.2e} 30 # or {:10.2e} could also work
Name (please print): Community Standard (print NetID): Problem III: [22 pts.] Plots (1) Write a script that will first ask the user for an integer N between 10 and 100; you may assume the user correctly enters a value. Create an N x1 matrix of uniformly distributed random numbers between 0 and 500 and call it rand_vals. Then have your code generate a plot of your random numbers using green diamonds not connected by lines. This plot does not need axis labels but should have a grid and be titled Random Numbers. Save the plot to a color Encapsulated Postscript file called rand_plot.eps. Then save the rand_vals data to a text file named rand_data.dat. (2) Write a script that will define a function called cossin that will take three arguments - two single frequencies and a matrix of times. The output should be defined as: cossin(ω 1,ω 2,t) = cos(ω 1 t) sin(ω 2 t) where denotes multiplication and the ω values are given in rad/s. Then use this function to make a single plot showing three different frequency combinations over a domain of 50 times between 0 to 2π. The frequencies and line styles should be: ω 1 ω 2 Style 1 2 Blue dashed line with blue circles at the points 1 3 Red dotted line with red squares at the points 2 3 Purple solid line with black pluses at the points You do not need a title, a grid, axis labels, or a title, nor do you need to save this figure. (3) Assuming your cossin function from above is working, and that you have already created a linearly spaced array of 50 times between 0 and 2π, write the additional code you would need to generate a figure with six different plots (all using black points connected by a solid black line) with the following frequency combinations: ω 1 = 1,ω 2 = 1 ω 1 = 1,ω 2 = 3 ω 1 = 1,ω 2 = 5 ω 1 = 2,ω 2 = 1 ω 1 = 2,ω 2 = 3 ω 1 = 2,ω 2 = 5 You do not need titles, grids, axis labels, or titles, nor do you need to save this figure.
1 # %% Imports 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 # %% (1) 6 N = int(input( ³Integer between 10 and 100: ³)) 7 rand_vals = np.random.uniform(0, 500, size=n) 8 9 plt.figure(1) 10 plt.clf() 11 plt.plot(rand_vals, ³gd ³) 12 plt.grid(1) 13 plt.title( ³Random Numbers ³) 14 plt.savefig( ³rand_plot.eps ³) 15 16 np.savetxt( ³rand_data.dat ³, rand_vals) 1 #%% Imports 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 #%% (2) 6 def cossin(w1, w2, t): 7 return np.cos(w1*t)*np.sin(w2*t) 8 9 plt.figure(1) 10 plt.clf() 11 tvals = np.linspace(0, 2*np.pi, 50) 12 13 plt.plot(tvals, cossin(1, 2, tvals), ³b--o ³) 14 plt.plot(tvals, cossin(1, 3, tvals), ³r:s ³) 15 plt.plot(tvals, cossin(2, 3, tvals), ³m-+ ³, markeredgecolor= ³k ³) 16 17 #%% (3) 18 plt.figure(2) 19 plt.clf() 20 plt.subplot(2, 3, 1) 21 plt.plot(tvals, cossin(1, 1, tvals), ³k.- ³) # k-. incorrect 22 plt.subplot(2, 3, 2) 23 plt.plot(tvals, cossin(1, 3, tvals), ³k.- ³) 24 plt.subplot(2, 3, 3) 25 plt.plot(tvals, cossin(1, 5, tvals), ³k.- ³) 26 plt.subplot(2, 3, 4) 27 plt.plot(tvals, cossin(2, 1, tvals), ³k.- ³) 28 plt.subplot(2, 3, 5) 29 plt.plot(tvals, cossin(2, 3, tvals), ³k.- ³) 30 plt.subplot(2, 3, 6) 31 plt.plot(tvals, cossin(2, 5, tvals), ³k.- ³) 32 33 #%% (3) in a loop 34 plt.figure(2) 35 plt.clf() 36 for row in range(2): 37 for col in range(3): 38 plt.subplot(2, 3, 3*row+col+1) 39 plt.plot(tvals, 40 cossin(row+1, 2*col+1, tvals), ³k.- ³) 41 42
43 #%% (3) future way: 44 fig, ax = plt.subplots(2, 3, num=2) 45 for row in range(2): 46 for col in range(3): 47 ax[row][col].plot(tvals, 48 cossin(row+1, 2*col+1, tvals), ³k.- ³)
Name (please print): Community Standard (print NetID): Problem IV: [24 pts.] Roy G. Functions The wavelength ranges for yellow, orange, and red light are (from Wikipedia): Color Minimum Wavelength (nm) Maximum Wavelength (nm) yellow 560 590 orange 590 635 red 635 700 (1) Write a function called wavelength that takes two inputs: the first (required) is a string while the second is an integer with a default value of 2. The function will have either one or two outputs depending on the value of the second input. In situations where the function is called with a 1 as the second input, the function should return the average wavelength (in nm) in the range for that color. In situations where the function is called with a 2 as the second input, the function should return two values in a tuple - the minimum wavelength and the maximum wavelength, both in nm. You may assume the user properly gives you a string, but if that string is not one of the three colors above, your function should raise a ValueError that says Unknown color. Here are some example runs: In [1]: wavelength(³yellow ³, 1) Out[1]: 575.0 In [2]: wavelength(³yellow ³) Out[2]: (560, 590) In [3]: (LowL, HighL) = wavelength(³red ³, 2) In [3]: print(lowl, HighL) 635 700 In [4]: wavelength(³blue ³) ( system messages) ValueError: Unknown color. (2) Write a function called rainbow.m that will take at least one input argument and returns one output. The first input will be a number representing a wavelength and the second, optional argument will be a value of 0 or 1 which will determine whether the function should print a line of information. Your function must validate the first input argument. If the user gives no input arguments, Python itself will give an error, rainbow() missing 1 required positional argument. If the user gives a first argument that is anything other than an int or a float the program should raise a ValueError: Single numerical value required. And if the user gives a first value that is outside the (inclusive) range of 560 to 700, the program should give an error, Unknown color. The second, optional argument is a print flag - if there is no second argument, the flag should be set to zero. You may assume if the user gives you a second argument they have done so correctly. Assuming the user gives a single appropriate value in the first argument, the program should return a string with the color name as given in the table above. Note: for 590 and 635, you can pick which color to call that. If the user has also given 1 as a second argument, the function should print a line stating the wavelength (as a float displaying the tenths digit) and the color. Here are some examples: In [1]: rainbow(630) Out[1]: ³orange ³ In [2]: rainbow(620, 1) Wavelength 620. 0 denotes orange. Out[2]: ³orange ³ In [3]: rainbow([600, 650]) ( system messages) ValueError: Single numerical value required In [4]: rainbow(1000) ( system messages) ValueError: Unknown color
1 def wavelength(color, outs=2): 2 if color == ³yellow ³: 3 minl = 560 4 maxl = 590 5 elif color == ³orange ³: 6 minl = 590 7 maxl = 635 8 elif color == ³red ³: 9 minl = 635 10 maxl = 700 11 else: 12 raise ValueError( ³Unknown color. ³) 13 14 if outs == 2: 15 return minl, maxl 16 else: 17 return (minl + maxl) / 2 1 def rainbow(wl, p=0): 2 if not isinstance(wl, (int, float)): 3 raise ValueError( ³ Single numerical value required. ³) 4 elif wl<500 or wl>700: 5 raise ValueError( ³ Unknown color ³) 6 7 if wl<590: 8 col_name = ³yellow ³ 9 elif wl<635: 10 col_name = ³orange ³ 11 else: 12 col_name = ³red ³ 13 14 if p==1: 15 print( ³Wavelength {:0.1f} denotes {:s}. ³.format(wl, col_name)) 16 17 return col_ name