ProgrammingModerateProduct-company MCQ pattern
Which key sorts records by score descending and then by name ascending, using one stable sort?
- A. sorted(rows, key=lambda r: (r.score, r.name), reverse=True)
- B. sorted(rows, key=lambda r: -r.score - r.total)
- C. sorted(rows, key=(r.score, r.name))
- D. sorted(rows, key=lambda r: (-r.score, r.name))
Correct answer: D. sorted(rows, key=lambda r: (-r.score, r.name))
Negating the numeric score sorts it descending while the name stays ascending in the same tuple. Reversing the tuple would also reverse the names, and a subtraction with a string or a bare tuple as key is an error.
More Python Programming questions
- What is the largest float that is less than 1.0 in Python, as printed by repr?
- What is printed? python print(3 // 2 2 + 3 % 2, -3 // 2 2 + -3 % 2)
- What is printed? python print('%s and %r' % ('a', 'a'))
- What is printed? python print('-'.join(map(str, range(3, 0, -1))))
- What is printed? python print('abc'[-1:-4:-1], 'abc'[5:], 'abc'[-10:2])
- What is printed? python print(ord('A') + 1, chr(ord('a') - 32))