ProgrammingHardProduct-company MCQ pattern
What is printed on the first line?
What is printed on the first line?
words = ['apple', 'Bob', 'cat', 'Dog', 'ant'] print(sorted(words, key=lambda w: (w[0].lower(), w))) print(sorted(words, key=lambda w: w.lower(), reverse=True))
- A. ['Bob', 'Dog', 'ant', 'apple', 'cat']
- B. ['apple', 'ant', 'Bob', 'cat', 'Dog']
- C. ['ant', 'apple', 'cat', 'Bob', 'Dog']
- D. ['ant', 'apple', 'Bob', 'cat', 'Dog']
Correct answer: D. ['ant', 'apple', 'Bob', 'cat', 'Dog']
The key sorts by the lowercase first letter and then by the full word, so 'ant' comes before 'apple' and 'Bob' comes before 'cat'. Ordering by the whole word would put capitals first, which is the trap.
More Python Programming questions
- What is printed on the second line? python nums = [5, -3, 0, 2, -3] print(sorted(nums, key=lambda x: x < 0)) print(sorted(nums, key=lambda…
- What is printed on the first line? python data = [('x', 3.0), ('y', 3), ('z', 2.5)] print(sorted(data, key=lambda t: t[1]))…
- What is printed? python s = 'level' t = ''.join(reversed(s)) print(s == t, s[::-1] is s, s[::-1] == t, s.count('l') s.count('e'))
- What is printed? python a = 1e308 b = a 10 print(b, -b, b - b if False else 0, b > a, b == float('inf'))
- What is printed? python import math print(math.sqrt(16), math.sqrt(2) 2 == 2, math.isqrt(2) 2 == 2, math.pow(2, 0.5) == 2 0.5)
- What is printed? python print(int(0.1 10) == 1, int(0.7 10), int(4.35 100), round(4.35 100))