# Initialize Otter
import otter
grader = otter.Notebook("Final_Exam_Practice.ipynb")
βοΈ Practice Final Exam#
This Practice Final Exam is designed to test your mastery of the Python programming language. You will be asked to respond to a series of questions both multiple choice and short answer problems using python. 10% of the points earned on this practice final prior to the exam will be added to your final exam score.
Instructions#
You are allowed to use anything with the python kernel to help you solve the problems. You must run all code and press the submit button when shown to record your grades. If you do not do this your scores might not be recorded. All of your responses should be persistent if you restart the kernel, however entries can only be updated if you run the cell and hit submit.
Part 1: Entering Your Information for Credit#
To receive credit for assignments, it is important we can identify your work from others. To do this, we will ask you to enter your information in the following code block.
You must hit submit and see the message saying the data is saved. If you do not see this message contact your instructor to ensure you are getting credit for your work.
Note: do not delete the output.log file or the .responses.json file or you might lose your current work.
Before you begin#
Run the block of code at the top of the notebook that imports and sets up the autograder. This will allow you to check your work.
import pkg_resources
from subprocess import call
import sys
package_name = 'ENGR131_Util_2024'
version = '1.0.0'
package_version = f'{package_name}=={version}'
try:
# Check if the package and version are installed
pkg_resources.require(package_version)
print(f'{package_version} is already installed.')
except pkg_resources.DistributionNotFound:
# If not installed, install the package
print(f'{package_version} not found. Installing...')
call([sys.executable, '-m', 'pip', 'install', package_version])
except pkg_resources.VersionConflict:
# If a different version is installed, you can choose to upgrade/downgrade
installed_packages = {dist.key: dist.version for dist in pkg_resources.working_set}
installed_version = installed_packages.get(package_name.lower())
print(f'{package_name} {installed_version} is installed, but {version} is required.')
# Optionally, upgrade or downgrade the package to the required version
call([sys.executable, '-m', 'pip', 'install', '--upgrade', package_version])
from ENGR131_Util_2024 import responses, StudentInfoForm, cell_logger
from ENGR131_Util_2024 import submit_question, ResponseStore, ValidateLogFile
# Register the log function to be called before any cell is executed
get_ipython().events.register('pre_run_cell', cell_logger)
responses["assignment"] = "practicefinal_1"
StudentInfoForm(**responses)
Question 1: Match the Correct Definition
18 points
Please run the block of code below and respond to the prompts with the most suitable response.
Make sure you hit the submit button or your grade will not be recorded. Confirmation that your responses are recorded will appear below the code block. We will only grade your most recent set of responses. You can submit entries as many times as you like.
# from ENGR131_Util_2024 import DataTypes
from ENGR131_Util_2024 import responses
from ENGR131_Util_2024 import TypesQuestion
TypesQuestion(**responses)
Question 2: Select the option that matches the definition
9 points
Please run the block of code below and respond to the prompts with the most suitable response.
Make sure you hit the submit button or your grade will not be recorded. Confirmation that your responses are recorded will appear below the code block. We will only grade your most recent set of responses. You can submit entries as many times as you like.
from ENGR131_Util_2024 import MCQQuestion
from ENGR131_Util_2024 import responses
MCQQuestion(**responses)
Question 3: Select all statements which are TRUE
20 points
Please run the block of code below and respond to the prompts with the most suitable response.
Make sure you hit the submit button or your grade will not be recorded. Confirmation that your responses are recorded will appear below the code block. We will only grade your most recent set of responses. You can submit entries as many times as you like.
from ENGR131_Util_2024 import responses
from ENGR131_Util_2024 import SelectMany
SelectMany(**responses)
Question 4: Reading and Interpreting Python Code
50 points
You are provided with the following code:
1 numbers = [5, 2, 3.0]
2 even = 0
3 odd = 0
4
5 while odd < 6:
6 for num in numbers:
7 if num % 2 == 0:
8 even += num
9 else:
10 odd += num
Please run the block of code below and respond to the prompts with the most suitable response.
Make sure you hit the submit button or your grade will not be recorded. Confirmation that your responses are recorded will appear below the code block. We will only grade your most recent set of responses. You can submit entries as many times as you like.
You will be asked to select the most relevant comment for the lines of code selected.
You will be asked to describe how the code is executed. Please use the debugger tool to help ensure you have a correct answer.
Line number: This is the line number of the code that is run during the execution of the code.
Variable Changed: This is the variable whose value is changed during the execution of the code. Note if no variable is changed - such as when evaluating logical expressions, select βNoneβ.
Current Value: This is the value of the variable after the line of code is executed. If a logical expression is evaluated, please enter the value of the logical expression.
DataType: This is the data type of the variable after the line of code is executed. If a logical expression is evaluated, please enter the data type of the logical expression.
Note: The autograder has mechanisms to provide partial credit. If you skip a step, it will continue grading at the next correct step.
We provide the code in Python for your convenience.
numbers = [5, 2, 3.0]
even = 0
odd = 0
while odd < 6:
for num in numbers:
if num % 2 == 0:
even += num
else:
odd += num
from ENGR131_Util_2024 import ReadingPythonQuestion
from ENGR131_Util_2024 import responses
ReadingPythonQuestion(**responses)
Question 5: Making a Graph#
35 points
A friend gives you a card with the following function written on it. You need to figure out what they are saying. Implement a function to reveal the hidden message.
Import the packages you need.
You will need
numpy
import this as the variablenp
You will need the
pyplot
module frommatplotlib
. Importpyplot
as a variableplt
.
Make a function called
draw_card_eq
.This should take one input
a
.Create a linearly-spaced vector using the
linspace
method innp
.The vector should go from 0 to \(2\pi\) with 2000 steps.
Assign this vector to the variable
t
.
Write the equation for
x
: $\( x = a(16(\sin(t))^3)\)$Write the equation for
y
: $\( y = a(13\cos(t) - 5\cos(2t) - 2\cos(3t) - \cos(4t))\)$Use the
plot
method inplt
to plotx
vsy
, set the plot color tored
using the inputred
as a stringSave this to the variable
plot_
.
Return
plot_
.
Call the function
draw_card_eq
witha
equal to 1. Doing so will reveal the message.Save the output of the function to a variable
plot_
.
# Your import statements go here.
# We would recommend checking this with the autograder.
# Completion of this step should pass tests 1-2.
...
# Your function goes here
# We would recommend checking this with the autograder.
# Completion of this step should pass test 3.
...
# Call your function here
# Make sure your check your code with the autograder. If you do not run the autograder your responses will not be graded.
# Completion of this step pass all tests.
...
grader.check("q5 - Making a Graph")
Recommended#
We recommend that you run the following code to ensure your responses are recorded. This is an extra measure to ensure your results are aaved.
submit_question()
Question 6: Using Data Types (30 Points)#
We have written a function that converts a DataType. Pass values with the expected DataTypes as defined below to the convert_to_string
function. The function will print the output.
Run the
convert_to_string
function first.Pass an integer
42
toconvert_to_string
.Save the output to a variable
int_
.
Pass an float
3.14159
toconvert_to_string
.Save the output to a variable
float_
.
Pass an boolean with a true value to
convert_to_string
.Save the output to a variable
bool_
.
Pass an string
I love coding
toconvert_to_string
.Save the output to a variable
string_
.
Pass a list of integers
1
,2
,3
toconvert_to_string
.Save the output to a variable
list_
.
Pass a tuple of values
a
,b
,c
toconvert_to_string
.Save the output to a variable
tuple_
.
Pass a dictionary with a key
name
and a valuejay
as a string and a keyage
and a value12
as an integer toconvert_to_string
.Save the output to a variable
dict_
.
def convert_to_string(data):
if isinstance(data, int):
print(data)
elif isinstance(data, float):
print("{:.2f}".format(data))
elif isinstance(data, bool):
print(str(data))
elif isinstance(data, str):
print(data)
elif isinstance(data, list):
elements = ", ".join([str(x) for x in data])
print(elements)
elif isinstance(data, tuple):
elements = ", ".join([str(x) for x in data])
print(elements)
elif isinstance(data, dict):
pairs = ", ".join(
["Key = " + str(k) + " Value = " + str(v) for k, v in data.items()]
)
print(pairs)
return data
# 1. Pass an integer `42` to `convert_to_string`.
# Save the output to a variable `int_`.
# completion of this step will pass test 1
...
# 2. Pass an float `3.14159` to `convert_to_string`.
# Save the output to a variable `float_`.
# completion of this step will pass test 2
...
# 3. Pass an boolean with a true value to `convert_to_string`.
# Save the output to a variable `bool_`.
# completion of this step will pass test 3
...
# 4. Pass an string `I love coding` to `convert_to_string`.
# Save the output to a variable `string_`.
# completion of this step will pass test 4
...
# 5. Pass a list of integers `1`, `2`, `3` to `convert_to_string`.
# Save the output to a variable `list_`.
# completion of this step will pass test 5
...
# 6. Pass a tuple of values `a`, `b`, `c` to `convert_to_string`.
# Save the output to a variable `tuple_`.
# completion of this step will pass test 6
...
# 7. Pass a dictionary with a key `name` and a value `jay` as a string and a key `age` and a value `12` as an integer to `convert_to_string`.
# Save the output to a variable `dict_`.
# completion of this step will pass test 7
...
grader.check("q6 - Exploring DataTypes")
Recommended#
We recommend that you run the following code to ensure your responses are recorded. This is an extra measure to ensure your results are aaved.
submit_question()
Question 7: Building a Thermometer (36 Points)#
In chemical engineering, it is common to monitor the temperature of a reactor. We will build a class to implement a temperature sensor. This sensor will save and also set a temperature value in Celsius. Additionally, the class will convert the temperature given in Celsius to Fahrenheit.
Build a class called
Thermometer
. This class will have to be initialized and have two methods.Add an initialization method that accepts an initial temperature in Celsius as a variable
temperature
.Save the
temperature
as an object attributetemperature_c
. This is the temperature in \(^{\circ}C\) .
Build a method
set_temperature
that will set the object attributetemperature_c
.This method takes one input
temperature
.We want to make sure the input is a number. Do this by trying to convert it to a
float
using the built infloat
method.If
temperature
is a number that can be converted to a float, save it to the object attributetemperature_c
.
If
temperature
cannot be converted to a float, set the object attributetemperature_c
to the string βfailβ.
Build a method
to_fahrenheit
that converts the temperature from Celsius to Fahrenheit.Convert the temperature using the following equation. $\(Fahrenheit = \frac{9}{5}Celsius +32 \)$
Return the temperature in Fahrenheit.
Instantiate a
Thermometer
water_sensor
with an initialtemperature
of12
\(^{\circ}C\).Extract the temperature in \(^{\circ}C\) from the object
water_sensor
.Assign the output to a variable
temp_c
.
Extract the temperature in \(^{\circ}F\) from the object
water_sensor
.Assign the output to a variable
temp_f
.
# Your class for Thermometer goes here
...
# Instantiate the Thermometer water_sensor here
...
# extract the temperature in degrees celsius
...
# extract the temperature in degrees fahrenheit
...
grader.check("q7-Building a Thermometer")
Recommended#
We recommend that you run the following code to ensure your responses are recorded. This is an extra measure to ensure your results are aaved.
submit_question()
Question 8: Determining a Price for a Circuit (40 Points)#
As an engineer, you might want to estimate the total price at which you would sell a circuit you designed based on the cost of goods from a supplier and a desired profit margin. We will write a Python function to assist you in this task.
We have provided you with two dictionaries, parts_cost
and circuit_parts
. parts_cost
defines the the parts from the supplier, and circuit_parts
defines the components needed to build the circuit. The circuit uses two Custom Processor
components, which are not available from the supplier, that each costs $12.
Cost of Goods from Supplier
Part Name (Key) |
Cost per Item (value, in $) |
---|---|
10-ohm resistor |
0.025 |
100-ohm resistor |
0.03 |
1-pF capacitor |
0.05 |
10-pF capacitor |
0.12 |
Components Required for Building the Circuit
Part Name (Key) |
Quantity (sub-key) |
Cost to Build (value, in $) |
---|---|---|
10-ohm resistor |
10 |
N/A |
10-pF capacitor |
3 |
N/A |
1-pF capacitor |
7 |
N/A |
Custom Processor |
2 |
12 |
Import the package
numpy
asnp
.You might not need to do this step if you have done it as part of the previous questions; however, it is good practice.
Define a function
price_calculator
that accepts three inputs:parts_cost
,circuit_parts
, andprofit
.Initialize a variable
cost_of_goods
, and set it equal to 0.Using a loop, compute the total
cost_of_goods
.You should use the
.items()
method of a dictionary that returns an iterator, where each iteration is a tuple containing the key and the value.You will need to use a branching statement to get the cost per item from the dictionary with the cost per item or the nested dictionary with the cost to build, whichever is appropriate for the part.
Determine the
sales_price
by adding the profit to thecost_of_goods
.Multiply the
cost_of_goods
by (1 +profit
).Using the
np.round
method, round the price to 2 decimal places.Save this value to the variable
sales_price
.
Call the
print_total
function withinprice_calculator
.Save the output to the variable
order_total
.
Print the variable
order_total
within theprice_calculator
function.Return the variable
sales_price
.
Call the function
price_calculator
with the inputsparts_cost
,circuit_parts
,profit
.Save the output to the variable
total_price
.
# Your import statement goes here.
...
parts_cost = {
"10-ohm resistor": 0.025,
"100-ohm resistor": 0.03,
"1-pF capacitor": 0.05,
"10-pF capacitor": 0.12,
}
circuit_parts = {
"10-ohm resistor": {"quantity": 10},
"10-pF capacitor": {"quantity": 3},
"1-pF capacitor": {"quantity": 7},
"Custom Processor": {"quantity": 2, "price": 12},
}
# profit assignment goes here, we have set this to 63%
profit = 0.63
# We have provided you with a function to print the total cost of the order
# you need to call this function but do not need to change it.
def print_total(sales_price):
return f"Total cost of the order: ${sales_price}"
# Your function price_calculator goes here
# Completion of this step should pass test 3
...
# Your call of the function price_calculator goes here
# Completion of this step should pass all tests
...
grader.check("q8-Determining a Price for a Circuit")
Recommended#
We recommend that you run the following code to ensure your responses are recorded. This is an extra measure to ensure your results are aaved.
submit_question()
Question 9: Plotting and Fitting (60 Points):#
One of the most common tasks in engineering is fitting data to a model. For this question we will generate some noisy data with a gaussian distribution - one of the most common statistical distributions. We will then plot this data, and fit this data to the model.
Start by importing the necessary tools. If you imported any of these packages before, you might not need to do so again; however, it is good practice.
Import
numpy
as the variablenp
.Import the
pyplot
module frommatplotlib
as a variableplt
.Import the function
curve_fit
fromscipy.optimize
.
Define a function
gaussian
that computes the Gaussian function using the following equation: $\(Ae^{\frac{-(x-b)^2}{2c^2}}\)$The function should accept inputs of
x
,a
,b
, andc
.
Use the
linspace
method innumpy
to generate a vector from-20
to20
with100
steps.Save this vector to the variable
x_data
.
Use the defined
gaussian
function to compute the true, resulting value whena
is3
,b
is4
, andc
is7
.Save this to the variable
y_true
.
Generate noisy data using the
random.normal
method innumpy
.The noisy data should be the same size as the
x_data
.Scale the noise by a factor of
0.3
, and add the noise they_true
variable.Assign the output to
y_noisy
.
Using the
scatter
method frommatplotlib
pyplot
, plot thex_data
vsy_noisy
.Add a label, βNoisy Dataβ.
Save this plot to the variable
plot_1
.
Use the imported
curve_fit
method to fit the noisy data to thegaussian
function over the range ofx_data
.Save the fit results to the variable
popt
, and the parameter covariances to a variablepcov
.Do not provide any initial guess, or provide
None
. If you provide an initial guess, the autograder might fail.
Calculate the fitted curve using the defined
gaussian
function.You can use the * method to unpack the list of fitted parameters if you like.
Save the result to a variable
y_fit
.
Plot the fit results as
x_data
vsy_fit
using theplot
method inpyplot
.Set the color of the line to green using the
g
tag.Add a label, βFitted Gaussianβ.
Save this plot to the variable
plot_2
.
Using the methods within
plt
, set thex_label
andy_label
tox
andy
, respectively.Use the
legend
method inplt
to add a legend.
# 1. Add your import statements here.
# Completion of this step will pass the first test
...
# do not delete the line of code below, it will cause problems with the autograder.
np.random.seed(42)
# 2. Define the Gaussian function.
# completion of this step will pass test 2.
...
# 3. define your x_data vector
# completion of this step will pass test 3.
...
# 4. Call the gaussian function as described above
# save the output to the variable y_true
# completion of this step will pass test 4.
...
#5. Generate the noisy data described above
# save the output to the variable y_noisy
# completion of this step will pass test 5.
...
# 6. Plot the noisy data using a scatterplot
# make sure to add the label "Noisy Data"
# save the output to the variable plot_1
...
# 7. Fit the noisy data to a Gaussian function using curve_fit
# save the outputs to the variables popt and pcov
# completion of this step will pass test 6.
...
# 8. Calculate the fitted curve using the gaussian function
# save the output to the variable y_fit
# completion of this step will pass test 7.
...
# 9. Plot the fitted results as described in the instructions
# save the output to the variable plot_2
# completion of this step will pass several more tests.
# make sure to add the label "Fitted Gaussian"
...
# 10. Add axis labels to the plot
# completion of this step will pass a test.
...
# 11. Add a legend to the plot
# completion of this step will pass all tests.
...
grader.check("q9-Plotting and Fitting")
Recommended#
We recommend that you run the following code to ensure your responses are recorded. This is an extra measure to ensure your results are aaved.
submit_question()
Validating your log file#
Before your submit your results we would recommend running the following command to validate your log file. This will ensure that you have followed the correct format and that your log file is valid.
ValidateLogFile("./output.log", responses["assignment"], 4)
Submitting Your Assignment#
To submit your assignment please use the following link the assignment on GitHub classroom.
Use this link to navigate to the assignment on GitHub classroom.
Please submit just your output.log file. No other files are needed.
If you need further instructions on submitting your assignment, please ask your TA during lab.
Viewing your score#
Each log
file you have uploaded will have a file with the name of your file + Grade_Report.md
. You can view this file by clicking on the file name. This will show you the results of the autograder.
Make sure you run your code, and run the tests. If you do not run the test you will not get credit for your work.
Note
In python and particularly jupyter notebooks it is common that during testing you run cells in a different order, or run cells and modify them. This can cause there to be local variables needed for your solution that would not be recreated on running your code again from scratch. Your assignment will be graded based on running your code from scratch. This means before you submit your assignment you should restart the kernel and run all cells. You can do this by clicking Kernel
and selecting Restart and Run All
. If you code does not run as expected after restarting the kernel and running all cells it means you have an error in your code.