ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE
What does the following Python 3 code print? d = {} for w in ["nut","kheer","tea","oat","nut","vada"]: d[w[0]] = d.get(w[0], 0) + 1 print(sorted(d.items()))
- A. [('kheer', 1), ('nut', 2), ('oat', 1), ('tea', 1), ('vada', 1)]
- B. [('a', 2), ('r', 1), ('t', 3)]
- C. [('k', 2), ('n', 3), ('o', 2), ('t', 2), ('v', 2)]
- D. [('k', 1), ('n', 2), ('o', 1), ('t', 1), ('v', 1)]
Correct answer: D. [('k', 1), ('n', 2), ('o', 1), ('t', 1), ('v', 1)]
Counting by first letter: get(key, 0)+1 builds a frequency map; sorted() orders the (key, count) pairs. Output: [('k', 1), ('n', 2), ('o', 1), ('t', 1), ('v', 1)].
More Python Programming questions
- What does the following Python 3 code print? s = "banana split" print("-".join(s.split("n")[1:]))
- What does the following Python 3 code print? from functools import lrucache calls = 0 @lrucache(None) def f(n): global calls calls += 1…
- What does the following Python 3 code print? a, b = set([12,12,1,7,1]), set([12,12,3,10,6,10]) print(sorted(a ^ b), len(a - b))
- What does the following Python 3 code print? def mk(): c = 0 def inc(): nonlocal c c += 2 return c return inc a, b = mk(), mk() for in…
- What does the following Python 3 code print? a, b, c = 25, 3, 17 print((a << b) ^ c, a & ~c, (a | c) >> b)
- What does the following Python 3 code print? def f(): try: return 7 finally: print("f", end=" ") x = f() + 13 print(x)