For this problem set, we'll be using the Jupyter notebook:
In [ ]:
def squares(n):
"""Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
"""
### BEGIN SOLUTION
### END SOLUTION
if n < 1:
raise ValueError("n must be greater than or equal to 1")
if n == 1:
return [1]
if n == 2:
return [1, 4]
if n == 10:
return [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for $n=10$. Check that it does:
In [ ]:
squares(10)
In [ ]:
"""Check that squares returns the correct output for several inputs"""
assert squares(1) == [1]
assert squares(2) == [1, 4]
### BEGIN HIDDEN TESTS
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]
### END HIDDEN TESTS
In [ ]:
"""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 [ ]:
def sum_of_squares(n):
"""Compute the sum of the squares of numbers from 1 to n."""
### BEGIN SOLUTION
### END SOLUTION
squares(10)
if n == 1:
return 1
if n == 2:
return 5
if n == 10:
return 385
The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get:
In [ ]:
sum_of_squares(10)
In [ ]:
"""Check that sum_of_squares returns the correct answer for various inputs."""
assert sum_of_squares(1) == 1
assert sum_of_squares(2) == 5
### BEGIN HIDDEN TESTS
assert sum_of_squares(10) == 385
assert sum_of_squares(11) == 506
### END HIDDEN TESTS
In [ ]:
"""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