ProgrammingHardTCS NQT · Accenture
What is printed?
What is printed?
print(sorted(['b10', 'b9', 'a100', 'c2'], key=lambda s: (s[0], int(s[1:]))))
- A. ['a100', 'b10', 'b9', 'c2']
- B. ['b9', 'b10', 'a100', 'c2']
- C. ['a100', 'b9', 'b10']
- D. ['a100', 'b9', 'b10', 'c2']
Correct answer: D. ['a100', 'b9', 'b10', 'c2']
The key sorts by the letter first and then by the numeric part, so b9 comes before b10 even though the string '10' is smaller than '9'.
More Python Programming questions
- What is printed? python print(sorted([-2, 1, 2, -1], key=abs))
- What is printed? python print('%5.1f|%-5d|' % (3.14159, 42))
- What is printed? python print(max(range(7), key=lambda i: (i % 3, i)))
- What is printed? python print(5 // 0.5, 5 % 0.5)
- What is printed? python print('xy'.replace('', '-'))
- What does this Python code print? a = [1, 2, 3] b = a a += [4] a = a + [5] print(b, a)