Modified Blackjack
Source: May 2025, Task 2 (DTU 02002/02003). Study solution — not an official answer key.
Problem
You have a stack of card values (list of ints, first element is the top). Remove n cards from the top so the next k cards sum exactly to 21.
Write modified_blackjack(cards) returning (n, k). If none exists, return (-1, -1). If several exist, choose the smallest n.
Example
>>> modified_blackjack([5, 2, 3, 9, 7, 6, 2, 4])
(1, 4)
Approach
Try each possible n from 0 upward. From the new top, add consecutive cards until the sum hits 21 (success) or exceeds 21 (try next n).
Solution
Show solution Hide solution
Solution
def modified_blackjack(cards):
for n in range(len(cards)):
total = 0
for k in range(1, len(cards) - n + 1):
total += cards[n + k - 1]
if total == 21:
return (n, k)
if total > 21:
break
return (-1, -1)