ProgrammingVery hardAmazon OA · Flipkart coding round
What is printed?
What is printed?
w = ['pear', 'fig', 'apple', 'kiwi', 'date'] print(sorted(w, key=lambda s: (len(s), s)), sorted(w, key=len, reverse=True))
- A. ['fig', 'date', 'kiwi', 'pear', 'apple'] ['apple', 'pear', 'kiwi', 'date', 'fig']
- B. ['fig', 'date', 'kiwi', 'pear', 'apple'] ['apple', 'pear', 'date', 'kiwi', 'fig']
- C. ['fig', 'date', 'kiwi', 'apple', 'pear'] ['apple', 'pear', 'kiwi', 'date', 'fig']
- D. ['fig', 'date', 'pear', 'kiwi', 'apple'] ['apple', 'pear', 'kiwi', 'date', 'fig']
Correct answer: A. ['fig', 'date', 'kiwi', 'pear', 'apple'] ['apple', 'pear', 'kiwi', 'date', 'fig']
The first sort orders by length and then alphabetically. With reverse=True and key=len, equal lengths keep their original order, so pear, kiwi and date stay in input order.
More Python Programming questions
- What is printed? python print(bool(0.0), bool(' '), bool(None is None), bool(float('nan')))
- What is printed? python def findmin(a): lo, hi = 0, len(a) - 1 while lo < hi: mid = (lo + hi) // 2 if a[mid] > a[hi]: lo = mid + 1 else…
- What is printed? python g = {'a': [3, 1], 'b': [2]} for v in g.values(): v.sort() print(g, sorted(g.items(), key=lambda kv: len(kv[1])…
- What is printed? python ops = {} for name in ['add', 'mul']: ops[name] = lambda x, y, n=name: x + y if n == 'add' else x y…
- What is printed? python print(list(enumerate('ab', start=1)), list(zip(reversed([1, 2, 3]), 'xyz')))
- What is printed? python print(hash(1) == hash(True), hash(-1) == -2)