ProgrammingHardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
rows = [(2, 'b'), (1, 'z'), (2, 'a'), (1, 'y')] print(sorted(rows, key=lambda t: (-t[0], t[1])))
- A. [(1, 'y'), (1, 'z'), (2, 'a'), (2, 'b')]
- B. [(2, 'b'), (2, 'a'), (1, 'z'), (1, 'y')]
- C. [(2, 'a'), (2, 'b'), (1, 'z'), (1, 'y')]
- D. [(2, 'a'), (2, 'b'), (1, 'y'), (1, 'z')]
Correct answer: D. [(2, 'a'), (2, 'b'), (1, 'y'), (1, 'z')]
The key negates the first field, so larger first values come earlier, and the second field breaks ties in ascending order. Negating a value is the usual trick for a descending sort key that can be combined with an ascending one.
More Python Programming questions
- What is printed? python print(sorted(['bb', 'a', 'cc', 'd', 'ee'], key=len, reverse=True))
- What is printed? python import bisect a = [1, 2, 2, 2, 3] print(bisect.bisectleft(a, 2), bisect.bisectright(a, 2), bisect.bisectright(a…
- What is printed? python import bisect print(bisect.bisectleft([5, 4, 3], 4))
- What is printed? python import bisect print(bisect.bisectleft([(1, 'a'), (3, 'b'), (5, 'c')], 3, key=lambda t: t[0]))
- What is printed? python import bisect a = [(1, 'x'), (4, 'y')] bisect.insort(a, (3, 'z'), key=lambda t: t[0]) print(a)
- What is printed? python import heapq h = [1, 3, 5] r = heapq.heapreplace(h, 0) print(r, sorted(h))