Predict the output
What does this print?
from itertools import combinations
prices, goal = [2, 3, 5, 7], 7
hits = [c for r in range(len(prices) + 1)
for c in combinations(prices, r) if sum(c) == goal]
print(len(hits), hits)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 2 [(7,), (2, 5)]
Right: 7 alone, and 2 with 5.
The brute-force check tries all 16 selections; the backtracking version reaches the same two without exploring branches that already overshoot.
Why not the others?
- B 3 [(7,), (2, 5), (2, 3)]. 2 and 3 add up to 5.
- C 1 [(2, 5)]. A single item can be a selection too.
Steps come from running the Python solution.
Text version
Prices 2, 3, 5 with goal 5:
- start: call
- take 2: call
- take 3: found
- skip 3: call
- take 5: pruned
- skip 5: call
- skip 2: call
- take 3: call
- take 5: pruned
- skip 5: call
- skip 3: call
- take 5: found
- skip 5: call
- take 3: call
- take 2: call
Result: 2 · 13 calls (call 9, found 2, pruned 2)
Prices 1, 2, 3, 4 with goal 4:
- start: call
- take 1: call
- take 2: call
- take 3: pruned
- skip 3: call
- take 4: pruned
- skip 4: call
- skip 2: call
- take 3: found
- skip 3: call
- take 4: pruned
- skip 4: call
- take 2: call
- skip 1: call
- take 2: call
- take 3: pruned
- skip 3: call
- take 4: pruned
- skip 4: call
- skip 2: call
- take 3: call
- take 4: pruned
- skip 4: call
- skip 3: call
- take 4: found
- skip 4: call
- take 3: call
- take 2: call
- take 1: call
Result: 2 · 25 calls (call 17, found 2, pruned 6)