Problem 3.4: Count Coins Tree (100 pts)
You want to help your friend learn tree recursion. They don't quite understand all the recursive calls and how they work, so you decide to make a tree of recursive calls to showcase the tree in tree in tree recursion. You pick the count_coins
problem.
Implement count_coins_tree
, which takes in a non-negative integer n and returns a tree representing the recursive calls of count change.
Since you don't want your trees to get too big, you decide to only include the recursive calls that eventually lead to a valid way of making change.
See the code below for an implementation of count_coins
.
def count_coins(change, denominations):
"""
Given a positive integer change, and a list of integers denominations,
a group of coins makes change for change if the sum of the values of
the coins is change and each coin is an element in denominations.
count_coins returns the number of such groups.
"""
if change == 0:
return 1
if change < 0:
return 0
if len(denominations) == 0:
return 0
without_current = count_coins(change, denominations[1:])
with_current = count_coins(change - denominations[0], denominations)
return without_current + with_current
For the times when either recursive call returns None
, you don't want to include that in your branches when making the tree. If both recursive calls return None
, then you want to return None
.
Each leaf for the count_coins_tree(15, [1, 5, 10, 25])
tree is one of these groupings.
- 15 1-cent coins
- 10 1-cent, 1 5-cent coins
- 5 1-cent, 2 5-cent coins
- 5 1-cent, 1 10-cent coins
- 3 5-cent coins
- 1 5-cent, 1 10-cent coin
Note: the label of your tree should be string.
def count_coins_tree(change, denominations):
"""
>>> count_coins_tree(1, []) # Return None since no ways to make change wuth no denominations
>>> t = count_coins_tree(3, [1, 2])
>>> print(t) # 2 ways to make change for 3 cents
3, [1, 2]
2, [1, 2]
2, [2]
1
1, [1, 2]
1
>>> # The tree that shows the recursive calls that result
>>> # in the 6 ways to make change for 15 cents
>>> t = count_coins_tree(15, [1, 5, 10, 25])
>>> print(t)
15, [1, 5, 10, 25]
15, [5, 10, 25]
10, [5, 10, 25]
10, [10, 25]
1
5, [5, 10, 25]
1
14, [1, 5, 10, 25]
13, [1, 5, 10, 25]
12, [1, 5, 10, 25]
11, [1, 5, 10, 25]
10, [1, 5, 10, 25]
10, [5, 10, 25]
10, [10, 25]
1
5, [5, 10, 25]
1
9, [1, 5, 10, 25]
8, [1, 5, 10, 25]
7, [1, 5, 10, 25]
6, [1, 5, 10, 25]
5, [1, 5, 10, 25]
5, [5, 10, 25]
1
4, [1, 5, 10, 25]
3, [1, 5, 10, 25]
2, [1, 5, 10, 25]
1, [1, 5, 10, 25]
1
"""
"*** YOUR CODE HERE ***"