ProgrammingVery hardProduct company OA

What is printed?

What is printed?
rows = [("x", 2), ("y", 1), ("z", 2), ("w", 1), ("v", 3)]
a = sorted(rows, key=lambda r: r[1], reverse=True)
b = sorted(rows, key=lambda r: -r[1])
c = sorted(sorted(rows), key=lambda r: r[1])
print("".join(r[0] for r in a), "".join(r[0] for r in b), "".join(r[0] for r in c), a == b)
  1. A. vzxwy vxzyw wyxzv False
  2. B. vxzyw vxzyw ywxzv True
  3. C. vxzyw vxzyw wyxzv True
  4. D. vzxwy vxzyw ywxzv False

Correct answer: C. vxzyw vxzyw wyxzv True

Python's sort is stable, and reverse=True is defined to keep that stability (equal keys stay in original order; it is not 'sort then reverse'). So a and b are identical: v, then x before z, then y before w → 'vxzyw'. For c the inner sort orders by name (v, w, x, y, z) and the stable outer sort by number keeps that order inside ties: w, y, x, z, v. 'vzxwy' is what reversing an ascending sort would give.

More Python Programming questions

Exams that ask this topic