ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
words = ["apple", "Banana", "cherry", "date"]
by_len = {}
for w in words:
by_len.setdefault(len(w), []).append(w)
print(by_len, {k: len(v) for k, v in sorted(by_len.items(), reverse=True)})- A. {5: ['apple'], 6: ['cherry'], 4: ['date']} {6: 1, 5: 1, 4: 1}
- B. {4: ['date'], 5: ['apple'], 6: ['Banana', 'cherry']} {6: 2, 5: 1, 4: 1}
- C. {5: ['apple'], 6: ['Banana', 'cherry'], 4: ['date']} {6: 2, 5: 1, 4: 1}
- D. {5: ['apple'], 6: ['Banana', 'cherry'], 4: ['date']} {4: 1, 5: 1, 6: 2}
Correct answer: C. {5: ['apple'], 6: ['Banana', 'cherry'], 4: ['date']} {6: 2, 5: 1, 4: 1}
setdefault creates each list on first sight of a length, so keys appear in first-seen order. Sorting the items in reverse orders them by key 6, 5, 4, and the dict comprehension keeps that order.
More Python Programming questions
- What is printed? python def outer(): results = [] def rec(n): if n == 0: results.append("x") return for in range(n): rec(n - 1) rec(3)…
- What is printed? python a = "abc" b = "".join(["a", "b", "c"]) print(a == b, a is b or True, sorted(set(a + b)), a.find("c") ==…
- What is printed? python temps = {"mon": 30, "tue": 25, "wed": 35} hot = [d for d, t in temps.items() if t > 28] coolest = min(temps…
- What is printed? python s = "level" t = "".join(reversed(s)) u = s[::-1] print(s == t == u, t is s, list(reversed([1, 2])) == [2, 1]…
- What is printed? python marks = [72, 85, 64, 85, 90] print(marks.index(85), marks.count(85), sorted(marks)[len(marks) // 2]…
- What is printed? python inventory = {"pen": 3, "ink": 0} inventory["pad"] = inventory.get("pad", 0) + 5 inventory.update(ink=2)…