ProgrammingModerateInfosys HackWithInfy · TCS CodeVita
What is printed?
What is printed?
from collections import defaultdict
words = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']
g = defaultdict(list)
for w in words:
g[''.join(sorted(w))].append(w)
print(list(g.values()))- A. [['eat', 'tea', 'ate'], ['bat'], ['tan', 'nat']]
- B. [['ate', 'eat', 'tea'], ['tan', 'nat'], ['bat']]
- C. [['tan', 'nat'], ['eat', 'tea', 'ate'], ['bat']]
- D. [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
Correct answer: D. [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
defaultdict keeps keys in first-seen order, and the sorted letters act as keys. eat, tea and ate share the key aet, then tan and nat share ant, and bat stands alone.
More Python Programming questions
- What is printed? python print(' a b '.split(' '), ' a b '.split(), 'a b x c d'.split(None, 1))
- What is printed? python from fractions import Fraction x = Fraction(1, 3) + Fraction(1, 6) print(x, x.numerator, Fraction(6, -8))
- What is printed? python print(format(255, '08b'), format(255, '#x'), '{:>5}|{:<3}|'.format(42, 7))
- What is printed? python def max3(a): a = sorted(a) return max(a[-1] a[-2] a[-3], a[0] a[1] a[-1]) print(max3([1, 2, 3, 4]), max3([-10…
- What is printed? python def g(): try: yield 1 yield 2 finally: print('cleanup') it = g() print(next(it)) it.close() print(list(it))
- What is printed? python print('hello world'.translate({ord('l'): None, ord('o'): 'O'}))