Skills Quiz - Python Edition Solutions

Similar documents
Skills Quiz - Python Edition Solutions

Test 1 - Python Edition

'XNH8QLYHUVLW\ (GPXQG73UDWW-U6FKRRORI(QJLQHHULQJ. EGR 103L Fall Skills Quiz. Rebecca A. Simmons and & Michael R.

Test 2 - Python Edition

'XNH8QLYHUVLW\ (GPXQG73UDWW-U6FKRRORI(QJLQHHULQJ. EGR 53L Fall Test I. Rebecca A. Simmons & W. Neal Simmons Michael R.

'XNH8QLYHUVLW\ (GPXQG73UDWW-U6FKRRORI(QJLQHHULQJ. EGR 53L Fall Test I. Rebecca A. Simmons & Michael R. Gustafson II

Intro to Research Computing with Python: Visualization

Lab 4: Structured Programming I

Computational Physics Programming Style and Practices & Visualizing Data via Plotting

CS 111X - Fall Test 1

Using the Matplotlib Library in Python 3

NAVIGATING UNIX. Other useful commands, with more extensive documentation, are

: Intro Programming for Scientists and Engineers Final Exam

MATPLOTLIB. Python for computational science November 2012 CINECA.

Visualisation in python (with Matplotlib)

Plotting With matplotlib

Scientific Programming. Lecture A08 Numpy

HW0 v3. October 2, CSE 252A Computer Vision I Fall Assignment 0

CS 111X - Fall Test 1 - KEY KEY KEY KEY KEY KEY KEY

CS150 Sample Final Solution

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

CS150 Sample Final. Name: Section: A / B

No more questions will be added


(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB

Partial Differential Equations II: 2D Laplace Equation on 5x5 grid

LECTURE 22. Numerical and Scientific Computing Part 2

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CS 111: Digital Image Processing Fall 2016 Midterm Exam: Nov 23, Pledge: I neither received nor gave any help from or to anyone in this exam.

Math-2. Lesson 3-1. Equations of Lines

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

Programming with Python

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

CMPSCI 119 Fall 2018 Wednesday, November 14, 2018 Midterm #2 Solution Key Professor William T. Verts

The SciPy Stack. Jay Summet

Topological Invariants with Z2Pack. Topological Matter School 2016, Donostia

Bi 1x Spring 2014: Plotting and linear regression

CS 1301 Exam 2 Fall 2010

1. Register an account on: using your Oxford address

Basic Beginners Introduction to plotting in Python

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

LAB 2: DATA FILTERING AND NOISE REDUCTION

Math 1MP3, final exam

CS 1301 Exam 1 Fall 2010

AMath 483/583 Lecture 28 June 1, Notes: Notes: Python scripting for Fortran codes. Python scripting for Fortran codes.

4. BASIC PLOTTING. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Introduction to Scientific Computing with Python, part two.

LAB 2: DATA FILTERING AND NOISE REDUCTION

Week Two. Arrays, packages, and writing programs

UNIVERSITETET I OSLO

ENGR (Socolofsky) Week 07 Python scripts

UNIVERSITETET I OSLO

#To import the whole library under a different name, so you can type "diff_name.f unc_name" import numpy as np import matplotlib.

PART 1 PROGRAMMING WITH MATHLAB

Introduction to Python Practical 1

Interpolation and curve fitting

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

egrapher Language Reference Manual

lof April 23, Improving performance of Local outlier factor with KD-Trees

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014)

Search. The Nearest Neighbor Problem

PS6-DCT-Soln-correction

Homework 11 - Debugging

CS 1110 Prelim 1 March 10, 2015

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Dr. Khalil Exam II Fall 2011

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( )

Python Crash Course Numpy, Scipy, Matplotlib

Test 2 Version A. On my honor, I have neither given nor received inappropriate or unauthorized information at any time before or during this test.

MATLAB SUMMARY FOR MATH2070/2970

Types, lists & functions

15-780: Problem Set #2

Spring 2017 CS 1110/1111 Exam 1

Matplotlib Python Plotting

ARTIFICIAL INTELLIGENCE AND PYTHON

User-Defined Function

MATLAB Introduction to MATLAB Programming

CS 1301 Post Exam 3 Practice Spring 2016

Neatly print first and last names: Exam II. "On my honor, as an Aggie, I have neither given nor received unauthorized aid on this academic work.

All written answers are limited to their question boxes. Make sure all answers are easily legible.

Page 1 of 7 E7 Spring 2009 Midterm I SID: UNIVERSITY OF CALIFORNIA, BERKELEY Department of Civil and Environmental Engineering. Practice Midterm 01

CS 1301 Exam 1 Fall 2014

Episode 8 Matplotlib, SciPy, and Pandas. We will start with Matplotlib. The following code makes a sample plot.

Adapted to TKT4140 Numerical Methods

This is a very quick intro to Python programming. Adapted to TKT4140 Numerical Methods. Mathematical example. A program for evaluating a formula

CS 1301 Exam 1 Fall 2010

Section 2 0: The Rectangular Coordinate System. The Coordinate System

Computer Lab 1: Introduction to Python

(the bubble footer is automatically inserted into this space)

ENGR Fall Exam 1

Sample Final Exam CSci 127: Introduction to Computer Science Hunter College, City University of New York

MAS212 Assignment #1 (2018): Rational approximations

Lab 6. COMP9021, Session 2, one solution is obtained by selecting 1 and both occurrences of 2 ( = 5);

Intermediate/Advanced Python. Michael Weinstein (Day 2)

CPSC 217 Midterm (Python 3 version)

Circle inversion fractals are based on the geometric operation of inversion of a point with respect to a circle, shown schematically in Fig. 1.

TMA4320 Tips for Python Coding

Fall 2017: Numerical Methods I Assignment 1 (due Sep. 21, 2017)

Transcription:

'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