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()))

  1. A. [('b', 3), ('c', 4), ('g', 4), ('j', 3), ('k', 5), ('n', 3)]
  2. B. [('b', 1), ('c', 1), ('g', 1), ('j', 1), ('k', 1), ('n', 1)]
  3. C. [('e', 2), ('m', 1), ('n', 1), ('r', 1), ('t', 1)]
  4. 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

Exams that ask this topic