ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def key_fn(p):
    return (-p[1], p[0])
people = [('bo', 3), ('al', 5), ('cy', 3)]
print([p[0] for p in sorted(people, key=key_fn)])
  1. A. ['bo', 'cy', 'al']
  2. B. ['al', 'bo']
  3. C. ['al', 'bo', 'cy']
  4. D. ['al', 'cy', 'bo']

Correct answer: C. ['al', 'bo', 'cy']

The key sorts by the second field descending, so al with 5 comes first. Ties at 3 are broken by the name ascending, which gives bo before cy.

More Python Programming questions

Exams that ask this topic