Predict the output
What does this print?
import heapq
pts = [[3, 4], [1, -1], [0, 2], [-2, 0]]
print(heapq.nsmallest(2, pts, key=lambda p: (p[0] ** 2 + p[1] ** 2, p)))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [[1, -1], [-2, 0]]
Right: squared distances are 25, 2, 4 and 4; the tie between 4s goes to the smaller x.
A key that includes the point itself turns ties into a fixed order, so every run gives the same answer.
Why not the others?
- B [[1, -1], [0, 2]]. [-2, 0] and [0, 2] tie on distance 4, and -2 < 0.
- C [[0, 2], [1, -1]]. Results come nearest first.