
Code
Treasure in Nested Chests
Recursion shines on data that contains smaller copies of itself: folders inside folders, comments with replies, chests inside chests.
def count_items(chest):
total = 0
for thing in chest:
if isinstance(thing, list):
total += count_items(thing) # a smaller chest!
else:
total += 1
return total
print(count_items(["gem", ["coin", ["ring"]], "map"])) # 4
A loop handles the items side by side; recursion handles the items inside each other. Here the base case is hidden: a chest with no inner chests simply never recurses.
Assignment
A chest is a list that holds whole numbers (gem values) and other chests.
count_gems(chest)returns the total value of every gem, however deep.count_gems([5, [10, [1, 2]], 3])is21.deepest(chest)returns how many levels of chests there are.deepest([1, 2])is1,deepest([1, [2, [3]]])is3,deepest([])is1.
A chest is a list that holds whole numbers (gem values) and other chests.
count_gems(chest)returns the total value of every gem, however deep.count_gems([5, [10, [1, 2]], 3])is21.deepest(chest)returns how many levels of chests there are.deepest([1, 2])is1,deepest([1, [2, [3]]])is3,deepest([])is1.
main.py Python sleeping
Press Run to try your code, then Check to test it.