ProgrammingVery hardProduct-company MCQ pattern
What is printed on the third line?
What is printed on the third line?
names = ['bob', 'Alice', 'carl', 'Bob', 'alice'] print(sorted(names)) print(sorted(names, key=str.casefold)) print(sorted(names, key=lambda s: (s.lower(), s)))
- A. ['Alice', 'alice', 'Bob', 'bob', 'carl']
- B. ['Alice', 'Bob', 'alice', 'bob', 'carl']
- C. ['Alice', 'alice', 'bob', 'carl', 'Bob']
- D. ['carl', 'Bob', 'bob', 'alice', 'Alice']
Correct answer: A. ['Alice', 'alice', 'Bob', 'bob', 'carl']
The tuple key compares the lowercase name first and the original text second, so for each name 'Alice' sorts before 'alice' and 'Bob' before 'bob'. Plain sorted() puts all capitals first, which is the trap.
More Python Programming questions
- What is printed? python x = 253 print(float(x + 1) == x, x + 1.0 == x, (x + 2.0) - x, int(float(x + 3)) - x)
- What is printed? python print([10, 20, 30][True], (5).bitlength(), (True).bitlength(), (-1).bitlength())
- What is printed? python print(round(7.5), round(6.5), round(-7.5), round(7.5000001))
- What is printed? python print(-7.5 % 2, 7.5 % -2, -0.0 % 3)
- What is printed? python words = 'the quick brown the lazy the'.split() counts = {} for w in words: counts[w] = counts.get(w, 0) + 1…
- What is printed? python print('%.3f' % 1.0005, '%.1f' % 0.25, '%.1f' % 0.35, round(0.35, 1))