ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from functools import cmp_to_key
w = ['bb', 'a', 'ccc', 'ab', 'c']
def c(x, y):
    if len(x) != len(y):
        return len(x) - len(y)
    return (y > x) - (y < x)
print(sorted(w, key=cmp_to_key(c)))
  1. A. ['c', 'a', 'bb', 'ab', 'ccc']
  2. B. ['a', 'c', 'ab', 'bb', 'ccc']
  3. C. ['a', 'c', 'bb', 'ab', 'ccc']
  4. D. ['c', 'a', 'ab', 'bb', 'ccc']

Correct answer: A. ['c', 'a', 'bb', 'ab', 'ccc']

Length is compared first, ascending. For equal lengths the comparator returns positive when y > x, which puts the larger string first, so the order is descending lexicographic within each length.

More Python Programming questions

Exams that ask this topic