Internals & Memory — Series 3

Preview — 3 of 10 questions

What is the output of the following code?

javascript
from collections.abc import Mapping

class ReadOnlyDict(Mapping):
    def __init__(self, data):
        self._data = dict(data)
    def __getitem__(self, key):
        return self._data[key]
    def __iter__(self):
        return iter(self._data)
    def __len__(self):
        return len(self._data)

rd = ReadOnlyDict({"a": 1, "b": 2})
print(rd["a"])
print(len(rd))
print(list(rd))
print(rd.get("z", "default"))

try:
    rd["a"] = 99
except TypeError as e:
    print("TypeError:", e)
A1, 2, ['a', 'b'], default, then TypeError: 'ReadOnlyDict' object does not support item assignment
BTypeError: Can't instantiate abstract class ReadOnlyDict with abstract methods __setitem__
C1, 2, ['a', 'b'], KeyError: 'z', then no error — rd["a"] is updated to 99
D1, 2, ['a', 'b'], default, then no error — rd["a"] is updated to 99

What is the output of the following code?

javascript
import heapq

a = [1, 4, 7]
b = [2, 3, 8]
c = [0, 5, 6]

merged = heapq.merge(a, b, c)
print(list(merged))
print(type(heapq.merge(a, b, c)))
A[1, 2, 0, 4, 3, 5, 7, 8, 6], <class 'generator'>
B[0, 1, 2, 3, 4, 5, 6, 7, 8], <class 'generator'>
C[1, 4, 7, 2, 3, 8, 0, 5, 6], <class 'list'>
D[0, 1, 2, 3, 4, 5, 6, 7, 8], <class 'list'>

What is the output of the following code?

javascript
import bisect

data = [{"n": 1}, {"n": 3}, {"n": 5}]
bisect.insort_left(data, {"n": 4}, key=lambda d: d["n"])
print(data)
A[{'n': 1}, {'n': 3}, {'n': 5}, {'n': 4}]
BTypeError: '<' not supported between instances of 'dict' and 'dict'
C[{'n': 1}, {'n': 3}, {'n': 4}, {'n': 5}]
D[{'n': 4}, {'n': 1}, {'n': 3}, {'n': 5}]

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.