Before you turn this problem in, make sure everything runs as expected. First, restart the kernel (in the menubar, select Kernel$\rightarrow$Restart) and then run all cells (in the menubar, select Cell$\rightarrow$Run All).
Make sure you fill in any place that says YOUR CODE HERE
or "YOUR ANSWER HERE", as well as your name and collaborators below:
In [1]:
NAME = "Alyssa P. Hacker"
COLLABORATORS = "Ben Bitdiddle"
For this problem set, we'll be using the Jupyter notebook:
In [2]:
def squares(n):
"""Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
"""
if n < 1:
raise ValueError
return [i ** 2 for i in range(1, n + 1)]
Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for $n=10$. Check that it does:
In [3]:
squares(10)
Out[3]:
In [4]:
"""Check that squares returns the correct output for several inputs"""
assert squares(1) == [1]
assert squares(2) == [1, 4]
assert squares(10) == [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
assert squares(11) == [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]
In [5]:
"""Check that squares raises an error for invalid inputs"""
try:
squares(0)
except ValueError:
pass
else:
raise AssertionError("did not raise")
try:
squares(-4)
except ValueError:
pass
else:
raise AssertionError("did not raise")
In [6]:
def sum_of_squares(n):
"""Compute the sum of the squares of numbers from 1 to n."""
return sum(squares(n))
The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get:
In [7]:
sum_of_squares(10)
Out[7]:
In [8]:
"""Check that sum_of_squares returns the correct answer for various inputs."""
assert sum_of_squares(1) == 1
assert sum_of_squares(2) == 5
assert sum_of_squares(10) == 385
assert sum_of_squares(11) == 506
In [9]:
"""Check that sum_of_squares relies on squares."""
orig_squares = squares
del squares
try:
sum_of_squares(1)
except NameError:
pass
else:
raise AssertionError("sum_of_squares does not use squares")
finally:
squares = orig_squares
$\sum_{i=1}^n i^2$
In [10]:
import math
def hypotenuse(n):
"""Finds the hypotenuse of a right triangle with one side of length n and
the other side of length n-1."""
# find (n-1)**2 + n**2
if (n < 2):
raise ValueError("n must be >= 2")
elif n == 2:
sum1 = 5
sum2 = 0
else:
sum1 = sum_of_squares(n)
sum2 = sum_of_squares(n-2)
return math.sqrt(sum1 - sum2)
In [11]:
print(hypotenuse(2))
print(math.sqrt(2**2 + 1**2))
In [12]:
print(hypotenuse(10))
print(math.sqrt(10**2 + 9**2))
$\sum x^i = \frac{1}{1-x}$