ProgrammingHardPython · GATE DA · Advanced
What is printed?
What is printed?
words = ['bb', 'a', 'cc', 'd', 'aa'] print(sorted(words, key=len, reverse=True)) print(sorted(words, key=lambda w: -len(w)))
- A. ['aa', 'cc', 'bb', 'd', 'a'] / ['aa', 'cc', 'bb', 'd', 'a']
- B. ['bb', 'cc', 'aa', 'a', 'd'] / ['bb', 'cc', 'aa', 'a', 'd']
- C. ['bb', 'cc', 'aa', 'a', 'd'] / ['aa', 'cc', 'bb', 'd', 'a']
- D. ['aa', 'cc', 'bb', 'd', 'a'] / ['bb', 'cc', 'aa', 'a', 'd']
Correct answer: B. ['bb', 'cc', 'aa', 'a', 'd'] / ['bb', 'cc', 'aa', 'a', 'd']
sorted with reverse=True preserves the original order of equal elements (stability is kept), exactly like the negated key; it is not the same as reversing the ascending result.
More Python Programming questions
- What is printed? python a = list(range(6)) a[1:4] = 'xy' print(a) try: a[::2] = [0, 0] except ValueError as e: print('VE') a[2:2] = [7]…
- What is printed? python a = [1, 2, 3] b = a b += [4] c = a c = c + [5] print(a, c)
- What is printed? python d = {'a': 1, 'b': 2} d['c'] = 3 del d['a'] d['a'] = 9 print(list(d.items()))
- What is printed? python s = "a,b,,c" print(s.split(','), s.split(',', 1), " x y ".split())
- What is printed? python print(list(zip('abc', range(5))), dict(zip('ab', [1, 2, 3])))
- What is printed? python def f(x, acc=[]): acc.append(x) return len(acc) print(f(1), f(2), f(3, []), f(4))