Lecture Code
1 | def fib_iter(n): |
1 | # Rational arithmetic |
1 | # Constructor and selectors |
Containers
1 | # Lists |
Q1: Taxicab Distance
An intersection in midtown Manhattan can be identified by an avenue and a street, which are both indexed by positive integers. The Manhattan distance or taxicab distance between two intersections is the number of blocks that must be traversed to reach one from the other, ignoring one-way street restrictions and construction. For example, Times Square is on 46th Street and 7th Avenue. Ess-a-Bagel is on 51st Street and 3rd Avenue. The taxicab distance between them is 9 blocks (5 blocks from 46th to 51st street and 4 blocks from 7th avenue to 3rd avenue). Taxicabs cannot cut diagonally through buildings to reach their destination!
Implement taxicab, which computes the taxicab distance between two intersections using the following data abstraction. Hint: You don’t need to know what a Cantor pairing function is; just use the abstraction.
1 | def intersection(st, ave): |
Q2:Squares only
Implement the function squares
, which takes in a list of positive integers. It returns a list that contains the square roots of the elements of the original list that are perfect squares. Try using a list comprehension.
You may find the round function useful.
1 | round(10.5) |
1 | from math import sqrt |
It might be helpful to construct a skeleton list comprehension to begin with:
1 | [sqrt(x) for x in s if is_perfect_square(x)] |
This is great, but it requires that we have an is_perfect_square function. How might we check if something is a perfect square?
If the square root of a number is a whole number, then it is a perfect square. For example, sqrt(61) = 7.81024… (not a perfect square) and sqrt(49) = 7 (perfect square).
Once we obtain the square root of the number, we just need to check if something is a whole number. The is_perfect_square function might look like:
1 | def is_perfect_square(x): |
One last piece of the puzzle: to check if a number is whole, we just need to see if it has a decimal or not. The way we’ve chosen to do it in the solution is to compare the original number to the round version (thus removing all decimals), but a technique employing floor division (//) or something else entirely could work too.
We’ve written all these helper functions to solve this problem, but they are actually all very short. Therefore, we can just copy the body of each into the original list comprehension, arriving at the solution we finally present.
Video walkthrough: https://youtu.be/YwLFB9paET0
We can also use pow
function to calculate the power of some number. And int(pow(n, 0.5)) == pow(n, 0.5)
can judge whether or nor n is perfect square number.
Q3:G function
A mathematical function G
on positive integers is defined by two cases:
1 | G(n) = n, if n <= 3 |
Write a recursive function g
that computes G(n)
. Then, write an iterative function g_iter
that also computes G(n)
:
Hint: The fibonacci
example in the tree recursion lecture is a good illustration of the relationship between the recursive and iterative definitions of a tree recursive problem.
1 | def g(n): |
The PDF solution
1 | def g_iter2(n): |
This is an example of how a function might be easier to write recursively versus iteratively. Since we have defined the g function in terms of older versions of itself, the solution tends very naturally towards recursion.
The iterative solution is trickier, since we can only track a finite amount of state at a given time. We need to pick our variables carefully so that we have just the information we need to calculate the next step. In a sense, this problem is very similar to the Fibonacci sequence (assuming we start at the 0th Fibonacci number):
1 | f(n) = n, if n <= 2 |
As you may recall, the solution for Fibonacci carried two variables around for the two previous values.
1 | def fib_iter(n): |
Since the g function depends on the three previous values, it might make sense that we might have to track three values instead!
Consider the three previous values old, older, and oldest. To do an update, the older value ages and becomes oldest, the old value ages and becomes older. Finally, old gets the new value which is derived from the three previous values: old + 2 * older + 3 * oldest.
Video walkthrough: https://youtu.be/pltx7u2kGGE
Q4: Count change
Once the machines take over, the denomination of every coin will be a power of two: 1-cent, 2-cent, 4-cent, 8-cent, 16-cent, etc. There will be no limit to how much a coin can be worth.
Given a positive integer amount
, a set of coins makes change for amount
if the sum of the values of the coins is amount
. For example, the following sets make change for 7
:
- 7 1-cent coins
- 5 1-cent, 1 2-cent coins
- 3 1-cent, 2 2-cent coins
- 3 1-cent, 1 4-cent coins
- 1 1-cent, 3 2-cent coins
- 1 1-cent, 1 2-cent, 1 4-cent coins
Thus, there are 6 ways to make change for7
. Write a recursive functioncount_change
that takes a positive integeramount
and returns the number of ways to make change foramount
using these coins of the future.
Hint: Refer the implementation of count_partitions
for an example of how to count the ways to sum up to an amount with smaller parts. If you need to keep track of more than one value across recursive calls, consider writing a helper function.
My solution: First find the largest denomination in our change, which is implemented by a while loop, then we find that the program is so like the count_partitions program, we think about this problem as either having the largest denomination or not having it. Then we use tree recursion to calculate the result.
1 | def count_change(amount): |
PDF solution, I think PDF solution is cleverer than mine, it uses the smallest denomination, which needn’t to implement a lessThanN
function, but the intrinsic mind is the same.
This is remarkably similar to the count_partitions problem, with a few minor differences:
- A maximum partition size m is not given, so we need to create a helper function that takes in two arguments and also create another helper function to find the max coin.
- Partition size is not linear, but rather multiples of two. To get the next partition you need to divide by two instead of subtracting one.
One other implementation detail here is that we enforce a maximum partition size, rather than a minimum coin. Many students attempted to start at 1 and work there way up. That will also work, but is less similar to count_partitions. As long as there is some ordering on the coins being enforced, we ensure we cover all the combinations of coins without any duplicates.
See the walkthrough for a more thorough explanation and a visual of the recursive calls. Video walkthrough: https://youtu.be/EgZJPNFnoxM.
1 | def count_change(amount): |
Q5: 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 with n
disks in a neat stack in ascending order of size on a start
rod, the smallest at the top, forming a conical shape.
The objective of the puzzle is to move the entire stack to an 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.
Complete the definition ofmove_stack
, which prints out the steps required to moven
disks from thestart
rod to theend
rod without violating the rules. The providedprint_move
function will print out the step to move a single disk from the givenorigin
to the givendestination
.
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 any n
. In your solution, take the recursive leap of faith whenever you need to move any amount of disks less than n
from one rod to another.
My solution: We can simply think this question as recursion. The base case is when n is 1, then we only need to move the disk from start to end, otherwise we first need to move n - 1 disks from start to median, which is calculated by 6 - start - end. Then we need to move the largest disk to the end rod. Last we need to move the median n - 1 disks to end rod.
1 | def print_move(origin, destination): |
The pdf solution:
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: https://youtu.be/VwynGQiCTFM
1 | def print_move(origin, destination): |
Q6: Anonymous factorial
The recursive factorial function can be written as a single expression by using a conditional expression.
1 | >>> fact = lambda n: 1 if n == 1 else mul(n, fact(sub(n, 1))) |
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 giving 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 in particular that 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:
1 | from operator import sub, mul |