23/28
Part 7 of 7 · What interviewers ask nextLearn and do
What interviewers ask next
Levels 3 and 4 of the practice problem are the first two follow-ups here, and the third is very large amounts. Each one reuses the table.
Return the coins: keep the coin that set each cell
def coins_used(amount: float, coins: list[float]) -> list[float] | None:
"""The coins themselves, or None if no mix makes the amount."""
by_cents = {round(c * 100): c for c in coins}
target, values = round(amount * 100), sorted(by_cents)
best = [0] + [math.inf] * target
# the coin that set best[t]
last = [0] * (target + 1)
for t in range(1, target + 1):
for v in values:
if v <= t and best[t - v] + 1 < best[t]:
best[t], last[t] = best[t - v] + 1, v
if best[target] == math.inf:
return None
used, t = [], target
while t:
used.append(by_cents[last[t]])
t -= last[t]
return used
print(coins_used(0.06, [0.01, 0.03, 0.04]))
What does coins_used(0.06, [0.01, 0.03, 0.04]) return?
Pick one to see what it prints.
Pick an answer above to see the rest