Predict the output
What does this print?
import heapq
ropes = [4, 3, 2, 6]
heapq.heapify(ropes)
cost = 0
while len(ropes) > 1:
joined = heapq.heappop(ropes) + heapq.heappop(ropes)
cost += joined
heapq.heappush(ropes, joined)
print(cost)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 29
Right: 2+3 = 5, then 4+5 = 9, then 6+9 = 15; 5 + 9 + 15 = 29.
Short ropes are counted in every later join, so putting them in first keeps the repeated part small.
Why not the others?
- B 15. That counts only the last join.
- C 34. Joining in the given order costs more.