Homework 5 Solutions
Solution Files
You can find the solutions in hw05.py.
Required Questions
Q1: Double Eights
Write a recursive function that takes in a positive integer n
and determines if its
digits contain two adjacent 8
s (that is, two 8
s right next to each other).
Hint: Start by coming up with a recursive plan: the digits of a number have double eights if either (think of something that is straightforward to check) or double eights appear in the rest of the digits.
Important: Use recursion; the tests will fail if you use any loops (for, while), the in
operator, or the str
function.
def double_eights(n: int) -> bool:
"""Returns whether or not n has two digits in row that
are the number 8.
>>> double_eights(1288)
True
>>> double_eights(880)
True
>>> double_eights(538835)
True
>>> double_eights(284682)
False
>>> double_eights(588138)
True
>>> double_eights(78)
False
>>> # ban iteration, in operator and str function
>>> from construct_check import check
>>> check(SOURCE_FILE, 'double_eights', ['While', 'For', 'In', 'Str'])
True
"""
last, second_last = n % 10, n // 10 % 10
if last == 8 and second_last == 8:
return True
elif n < 100:
return False
return double_eights(n // 10)
# Alternate solution
last, second_last = n % 10, n // 10 % 10
if n < 10:
return False
return (last == 8 and second_last == 8) or double_eights(n // 10)
# Alternate solution with helper function:
def helper(num, prev_eight):
if num == 0:
return False
if num % 10 == 8:
if prev_eight:
return True
return helper(num // 10, True)
return helper(num // 10, False)
return helper(n, False)
Use Ok to test your code:
python3 ok -q double_eights
Q2: Add Characters
Given two words, w1
and w2
, we say w1
is a subsequence of w2
if all the letters in w1
appear in w2
in the same order (but
not necessarily all together). That is, you can add letters to any position in
w1
to get w2
.
For example, "sing" is a substring of "absorbing" and "cat" is a substring of
"contrast".
Implement add_chars
, which takes in w1
and w2
, where w1
is a substring of w2
. This means that w1
is shorter than w2
. It should
return a string containing the characters you need to add to w1
to get w2
. Your solution
must use recursion.
In the example above, you need to add the characters "aborb" to "sing" to get "absorbing", and you need to add "ontrs" to "cat" to get "contrast".
The letters in the string you return should be in the order you have to add them from left to right.
If there are multiple characters in the w2
that could correspond to characters in w1
, use the
leftmost one. For example, add_words("coy", "cacophony")
should return "acphon", not "caphon"
because the first "c" in "coy" corresponds to the first "c" in "cacophony".
def add_chars(w1, w2):
"""
Return a string containing the characters you need to add to w1 to get w2.
You may assume that w1 is a subsequence of w2.
>>> add_chars("owl", "howl")
'h'
>>> add_chars("want", "wanton")
'on'
>>> add_chars("rat", "radiate")
'diae'
>>> add_chars("a", "prepare")
'prepre'
>>> add_chars("resin", "recursion")
'curo'
>>> add_chars("fin", "effusion")
'efuso'
>>> add_chars("coy", "cacophony")
'acphon'
>>> from construct_check import check
>>> # ban iteration and sets
>>> check(SOURCE_FILE, 'add_chars',
... ['For', 'While', 'Set', 'SetComp']) # Must use recursion
True
"""
if not w1:
return w2
elif w1[0] == w2[0]:
return add_chars(w1[1:], w2[1:])
return w2[0] + add_chars(w1, w2[1:])
Use Ok to test your code:
python3 ok -q add_chars
Q3: Sublist
Write a function has_sublist
that takes two lists, lst
and sublist
, and returns whether the elements of sublist
appear consecutively in order anywhere within lst
.
def has_sublist(lst, sublist):
"""Returns whether the elements of sublist appear consecutively in order anywhere within lst.
>>> has_sublist([], [])
True
>>> has_sublist([3, 3, 2, 1], [])
True
>>> has_sublist([], [3, 3, 2, 1])
False
>>> has_sublist([3, 3, 2, 1], [3, 2, 1])
True
>>> has_sublist([3, 2, 1], [3, 2, 1])
True
>>> has_sublist([4, 3, 2, 1], [4, 2, 1])
False
>>> has_sublist([9, 3, 2, 1, 9], [3, 2, 1])
True
"""
sublist_length = len(sublist)
lst_length = len(lst)
if sublist_length > lst_length:
return False
elif lst[:sublist_length] == sublist:
return True
else:
return has_sublist(lst[1:], sublist)
Use Ok to test your code:
python3 ok -q has_sublist
Just For Fun Questions
The questions below are optional and not representative of exam questions. You can try them if you want an extra challenge, but they're just puzzles that are not required for the course. Almost all students will skip them, and that's fine. We will not be prioritizing support for these questions on Ed or during office hours.
Q4: Towers of Hanoi
A classic puzzle called the Towers of Hanoi is a game that consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts withn
disks in a neat stack in ascending order of size on
a start
rod, the smallest at the top, forming a conical shape.

end
rod,
obeying the following rules:
- Only one disk may be moved at a time.
- Each move consists of taking the top (smallest) disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
- No disk may be placed on top of a smaller disk.
move_stack
, which prints out the steps required to
move n
disks from the start
rod to the end
rod without violating the
rules. The provided print_move
function will print out the step to move a
single disk from the given origin
to the given destination
.
Hint: Draw out a few games with various
n
on a piece of paper and try to find a pattern of disk movements that applies to anyn
. In your solution, take the recursive leap of faith whenever you need to move any amount of disks less thann
from one rod to another. If you need more help, see the following hints.
The strategy used in Towers of Hanoi is to move all but the bottom disc to the second peg, then moving the bottom disc to the third peg, then moving all but the second disc from the second to the third peg.
One thing you don't need to worry about is collecting all the steps.
print
effectively "collects" all the results in the terminal as long as you
make sure that the moves are printed in order.
def print_move(origin, destination):
"""Print instructions to move a disk."""
print("Move the top disk from rod", origin, "to rod", destination)
def move_stack(n, start, end):
"""Print the moves required to move n disks on the start pole to the end
pole without violating the rules of Towers of Hanoi.
n -- number of disks
start -- a pole position, either 1, 2, or 3
end -- a pole position, either 1, 2, or 3
There are exactly three poles, and start and end must be different. Assume
that the start pole has at least n disks of increasing size, and the end
pole is either empty or has a top disk larger than the top n start disks.
>>> move_stack(1, 1, 3)
Move the top disk from rod 1 to rod 3
>>> move_stack(2, 1, 3)
Move the top disk from rod 1 to rod 2
Move the top disk from rod 1 to rod 3
Move the top disk from rod 2 to rod 3
>>> move_stack(3, 1, 3)
Move the top disk from rod 1 to rod 3
Move the top disk from rod 1 to rod 2
Move the top disk from rod 3 to rod 2
Move the top disk from rod 1 to rod 3
Move the top disk from rod 2 to rod 1
Move the top disk from rod 2 to rod 3
Move the top disk from rod 1 to rod 3
"""
assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"
if n == 1:
print_move(start, end)
else:
other = 6 - start - end
move_stack(n-1, start, other)
print_move(start, end)
move_stack(n-1, other, end)
Use Ok to test your code:
python3 ok -q move_stack
To solve the Towers of Hanoi problem for n
disks, we need to do three
steps:
- Move everything but the last disk (
n-1
disks) to someplace in the middle (not the start nor the end rod). - Move the last disk (a single disk) to the end rod. This must occur after step 1 (we have to move everything above it away first)!
- Move everything but the last disk (the disks from step 1) from the middle on top of the end rod.
We take advantage of the fact that the recursive function move_stack
is
guaranteed to move n
disks from start
to end
while obeying the rules
of Towers of Hanoi. The only thing that remains is to make sure that we
have set up the playing board to make that possible.
Since we move a disk to end rod, we run the risk of move_stack
doing an
improper move (big disk on top of small disk). But since we're moving the
biggest disk possible, nothing in the n-1
disks above that is bigger.
Therefore, even though we do not explicitly state the Towers of Hanoi
constraints, we can still carry out the correct steps.
Video walkthrough:
Q5: Anonymous Factorial
This question demonstrates that it's possible to write recursive functions without assigning them a name in the global frame.
The recursive factorial function can be written as a single expression by using a conditional expression.
>>> fact = lambda n: 1 if n == 1 else mul(n, fact(sub(n, 1)))
>>> fact(5)
120
However, this implementation relies on the fact (no pun intended) that
fact
has a name, to which we refer in the body of fact
. To write a
recursive function, we have always given it a name using a def
or
assignment statement so that we can refer to the function within its
own body. In this question, your job is to define fact
recursively
without using a def
or assignment statement to give it a name.
Write an expression that computes n
factorial using only call
expressions, conditional expressions, and lambda
expressions (no
assignment or def
statements).
Note: You are not allowed to use
make_anonymous_factorial
in your return expression.
The sub
and mul
functions from the operator
module are the only
built-in functions required to solve this problem.
Hint: In order to recursively compute the factorial, you need a name to use in the recursive calls. What other ways have we learned to give something a name, besides assignment statements and
def
statements?
from operator import sub, mul
def make_anonymous_factorial():
"""Return the value of an expression that computes factorial.
>>> make_anonymous_factorial()(5)
120
>>> from construct_check import check
>>> # ban any assignments or recursion
>>> check(SOURCE_FILE, 'make_anonymous_factorial',
... ['Assign', 'AnnAssign', 'AugAssign', 'NamedExpr', 'FunctionDef', 'Recursion'])
True
"""
return (lambda f: lambda k: f(f, k))(lambda f, k: k if k == 1 else mul(k, f(f, sub(k, 1))))
# Alternate solution:
return (lambda f: f(f))(lambda f: lambda x: 1 if x == 0 else x * f(f)(x - 1))
Use Ok to test your code:
python3 ok -q make_anonymous_factorial
Check Your Score Locally
You can locally check your score on each question of this assignment by running
python3 ok --score
This does NOT submit the assignment! When you are satisfied with your score, submit the assignment to Gradescope to receive credit for it.
Submit Assignment
Submit this assignment by uploading any files you've edited to the appropriate Gradescope assignment. Lab 00 has detailed instructions.