ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
from collections import namedtuple
P = namedtuple("P", "x y", defaults=[0])
p = P(1)
q = p._replace(y=5)
print(p, q, p == (1, 0), q._asdict()["y"], P._fields)- A. P(x=1, y=None) P(x=1, y=5) False 5 ('x', 'y')
- B. P(x=1, y=0) P(x=1, y=5) True 5 ('x', 'y')
- C. P(x=1, y=0) P(x=1, y=0) True 5 ('x', 'y')
- D. P(x=1, y=0) P(x=1, y=5) False 5 ['x', 'y']
Correct answer: B. P(x=1, y=0) P(x=1, y=5) True 5 ('x', 'y')
defaults apply to the rightmost fields, so y defaults to 0. _replace returns a NEW namedtuple (they are immutable). A namedtuple is a tuple, so it compares equal to a plain tuple with the same items.
More Python Programming questions
- What is printed? python from dataclasses import dataclass, field @dataclass class Item: name: str tags: list = field(defaultfactory=list)…
- What is printed? python from dataclasses import dataclass @dataclass(frozen=True) class Pt: x: int y: int = 0 p = Pt(1) try: p.x = 5…
- What is printed? python nums = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda n: n % 2 == 0, nums)) total = sum(n n for n in nums if n % 2)…
- What is printed? python def chunks(xs, k): for i in range(0, len(xs), k): yield xs[i:i + k] def flatten(seq): for s in seq: if…
- What is printed? (Output lines are shown separated by " / ".) python def f(a, b, /, c, , d): return (a, b, c, d) args = (1, 2) kw = {"c"…
- What is printed? python class A: def init(self, kw): print("A", sorted(kw), end=" ") class B(A): def init(self, b=0, kw): print("B", end="…