ProgrammingHardTCS CodeVita · Infosys HackWithInfy · Product Company SDE
What does the following Python 3 code print? d = {} for w in ["kheer","ghee","bun","nut","cake","jam"]: d[w[0]] = d.get(w[0], 0) + 1 print(sorted(d.items()))
- A. [('b', 3), ('c', 4), ('g', 4), ('j', 3), ('k', 5), ('n', 3)]
- B. [('b', 1), ('c', 1), ('g', 1), ('j', 1), ('k', 1), ('n', 1)]
- C. [('e', 2), ('m', 1), ('n', 1), ('r', 1), ('t', 1)]
- D. [('b', 2), ('c', 2), ('g', 2), ('j', 2), ('k', 2), ('n', 2)]
Correct answer: B. [('b', 1), ('c', 1), ('g', 1), ('j', 1), ('k', 1), ('n', 1)]
Counting by first letter: get(key, 0)+1 builds a frequency map; sorted() orders the (key, count) pairs. Output: [('b', 1), ('c', 1), ('g', 1), ('j', 1), ('k', 1), ('n', 1)].
More Python Programming questions
- What does the following Python 3 code print? a, b = 18, 5 print(a // b, a % b, -a // b, -a % b)
- What does the following Python 3 code print? a = [[0] 2] 2 a[0][0] = 7 print(a)
- What does the following Python 3 code print? print(sum(x x for x in range(30) if x % 4 == 1))
- What does the following Python 3 code print? def f(x, acc=[]): acc.append(x) return acc f(8) f(4) print(f(8))
- What does the following Python 3 code print? fs = [lambda: i 2 for i in range(4)] print([f() for f in fs])
- What does the following Python 3 code print? a, b = set([2,10,5,12,11,10]), set([12,5,9,3]) print(sorted(a ^ b), len(a - b))