Exercises¶
Problem 0
Follow the instructions on Setting Up Google Colab to create a copy of the Google Colab template notebook for this lab. Type the following into a Code cell in your new notebook.
print("Hello, world!")
Execute the cell with shift+enter.
You should see the message printed below the cell.
Hello, world!
You have just executed a single line of Python code!
Problem 1
Suppose the local creamery has the following menu items.
Box of French fries, $2.49
Guacamole bacon burger, $8.69
Single scoop of ice cream, $3.99
There is a 7.45% sales tax on all purchases, and you happen to have a $5.00 coupon. The following code creates variables for each of these quantities.
# Menu item prices.
fries = 2.49
guac_burger = 8.69
ice_cream = 3.99
# Taxes and coupon value.
tax_rate = 0.0745 # 7.45%
coupon = 5.00
For an order of 3 fries, 2 burgers, and 2 ice creams, use the variables defined above to calculate and store the following quantities.
Subtotal: the total cost of the order before tax or discounts.
Store this value in a variableproblem1_subtotal.Tax: the subtotal (use
problem1_subtotal) multiplied by the tax rate.
Store this value in a variableproblem1_tax.Total: the subtotal plus the tax (use
problem1_tax) minus the value of the coupon.
Store this value in a variableproblem1_total.
Test Cases
Solutions to most exercises in this class can be verified with appropriate tests. For this problem, you could calculate each quantity by hand and compare your results. As an additional spot check, if only 2 of each item were ordered, then the variables would have the following values.
print(problem1_subtotal)
print(problem1_tax)
print(problem1_total)
30.34
2.2603299999999997
27.60033
After running this check, remember to change the code back to the original order of 3 fries.
Don’t Overwrite Answers
Do not redefine the variables problem1_subtotal, problem1_tax, or problem1_total later in your notebook.
The autograder only reads the final value of the variable at the end of the notebook.
Problem 2
For \(0 < x \le 2\), the natural logarithm \(\ln(x)\) can be written as the infinite series
This is called the Taylor series for \(\ln(x)\) centered around \(x = 1\). Although a computer cannot add up infinitely many numbers (it would take infinitely many computations), the sum can be approximated by adding together the first several terms.
Write a function named natural_log() that accepts a float representing \(x\) and returns an estimate for \(\ln(x)\) using the first 5 terms of the above series.
That is, natural_log(x) should return the number
which will be close to the true value of \(\ln(x)\) if \(x\) is near \(1\). Include a brief docstring describing the function.
Spelling Matters
The functions in this and the following problems must be named exactly as described, otherwise the autograder will not be able to find and test them.
Test Cases
To test your function, call it with a few different input values using the following code and compare the results to those listed below.
print(natural_log(0.8))
print(natural_log(1.0))
print(natural_log(1.2))
-0.22313066666666664
0.0
0.18233066666666664
Spot Checks Don’t Guarantee Correctness
This test is only a spot check! Matching given outputs does not guarantee that the function always returns the right result for every possible input. However, if the outputs do not match (or if calling the function raises an error), this indicates that something is wrong with the function definition or the arguments being used.
Problem 3
Euler’s constant \(e\) is the base of the exponential function \(e^x\). One way to define \(e\) is as the limit
To estimate this limit, we can compute \((1 + \frac{1}{n})^n\) for a large (but finite) number \(n\). The following function implements this idea.
def exponential_constant(n):
"""Estimate Euler's constant e as (1 + 1/n)^n for the given n."""
return (1 + (1 / n)) ** n
Like the function natural_log() from Problem 2, the function exponential_constant() only computes an approximation.
To check how good the approximation is, we can use the fact that the exponential and natural logarithm are inverses: \(e^{\ln(x)} = x\), so then \(x - e^{\ln(x)} = 0\).
Write a function named explog_error() that accepts two arguments (in this order):
A
floatrepresenting \(x\), andAn
intorfloatrepresenting \(n\).
Compute and return the difference
\(
x - e^{\ln(x)}
\)
where \(e\) is estimated with exponential_constant() and \(\ln(x)\) is estimated with natural_log().
Test Cases
print(explog_error(1.314, 2))
print(explog_error(1.314, 10))
print(explog_error(1.314, 50))
0.06599324187790923
0.016565007091014605
0.003372826007180585
Problem 4
Recall the creamery from Problem 1 that has the following menu items.
Box of French fries, $2.49
Guacamole bacon burger, $8.69
Single scoop of ice cream, $3.99
Write a function named creamery_bill() that accepts three int arguments (in this order):
The number of boxes of French fries to order.
The number of guacamole bacon burgers to order.
The number of single scoop ice creams to order.
Calculate the total cost of the order with the given numbers of items, including the 7.45% tax and the $5.00 coupon. Return the result, rounded to the nearest cent (two decimal places).
Test Cases
print(creamery_bill(2, 2, 2)) # 2 of each
print(creamery_bill(1, 2, 3)) # 1 fries, 2 burgers, 3 ice creams
print(creamery_bill(0, 3, 5)) # 3 burgers, 5 ice creams
27.6
29.21
44.45
Additionally, creamery_bill(3, 2, 2) should nearly equal problem1_total (with perhaps a small difference due to rounding).
Problem 5
One inch equals 2.54 centimeters. Therefore,
There are 12 inches in a foot.
Write a function named cm2ftin() that accepts a single argument representing a length in centimeters.
Convert the length to inches, round the total number of inches to the nearest whole inch, then return two values: the number of feet and the remaining inches.
Test Cases
# 2.54 centimeters = 0 feet, 1 inch
feet, inches = cm2ftin(2.54)
print(feet)
print(inches)
0
1
# 1000 centimeters = 10 meters = 32 feet, 9.7 inches
feet, inches = cm2ftin(1000)
print(feet)
print(inches)
32
10
Problem 6
Consider the following piecewise function.
The graph of \(f(x)\) is displayed below.
Write a function named piecewise() that accepts a single argument representing \(x\) and returns the value of \(f(x)\).
Test Cases
print(piecewise(-1.5))
print(piecewise(0.0))
print(piecewise(0.5))
print(piecewise(3000))
0.5
0.0
0.25
1.0
Problem 7
Recall the creamery from Problem 1 and Problem 4 that has the following menu items.
Box of French fries, $2.49
Guacamole bacon burger, $8.69
Single scoop of ice cream, $3.99
Suppose the creamery has two special deals:
If a customer pays with a special campus card, there is no tax charge.
If, after tax is added, the coupon is subtracted, and the result is rounded to the nearest cent, the total bill is a whole-dollar amount (\(x\) dollars and zero cents), then there is an additional $1.00 discount. For example, if the rounded total after tax and coupon is exactly $5.00, then the cost is decreased to $4.00; if the rounded total is $5.01, there is no special discount.
Write a function named creamery_special() that accepts the following arguments (in order):
The number of boxes of French fries to order.
The number of guacamole bacon burgers to order.
The number of single scoop ice creams to order.
Whether the campus card is used to pay (
Trueif yes,Falseif not).
Calculate the total cost of the order with the given numbers of items: start from the subtotal, add the 7.45% tax unless the campus card is used, subtract the $5.00 coupon, round to the nearest cent, and apply the additional $1.00 special discount if applicable.
If the total is negative after all discounts, return zero. Otherwise, return the total (still rounded to the nearest cent).
Hint 1: The % operator may be useful for the special discount.
print(6.41 % 1)
print(7.92 % 1)
print(8.00 % 1)
0.41000000000000014
0.9199999999999999
0.0
Hint 2: A variable of type bool can be used as the entire conditional of an if clause.
boolean_variable = True
if boolean_variable:
print("It's True!")
else:
print("It's False.")
It's True!
Test Cases
print(creamery_special(2, 2, 2, False)) # 2 of each, without the campus card.
print(creamery_special(1, 2, 3, True)) # An order with the campus card.
print(creamery_special(5, 1, 1, False)) # An order with the special discount.
print(creamery_special(2, 3, 5, True)) # An order with the special discount.
print(creamery_special(0, 0, 1, True)) # A subtotal less than the coupon.
27.6
26.84
21.0
45.0
0.0