Data Structures & AlgorithmsModerateTCS NQT · Python basics

Problem: What does the following print?

Problem: What does the following print?
ops = [('b', 2), ('a', 2), ('c', 1), ('d', 3)]
print([x for x, _ in sorted(ops, key=lambda t: -t[1])])
  1. A. ['d', 'a', 'b', 'c']
  2. B. ['b', 'a', 'd', 'c']
  3. C. ['d', 'b', 'c', 'a']
  4. D. ['d', 'b', 'a', 'c']

Correct answer: D. ['d', 'b', 'a', 'c']

Python's sort is stable, so the two items with value 2 keep their original order b before a. Sorting by -value gives d (3), then b, a (2) and c (1).

More Coding Interview Problems questions

Exams that ask this topic