ProgrammingVery hardProduct company OA
What is printed?
What is printed?
def reg(name, seen={}, order=[]):
if name not in seen:
seen[name] = len(order)
order = order + [name]
return seen[name], len(order)
print(reg("a"), reg("b"), reg("a"), reg("c"))- A. (0, 1) (1, 2) (0, 2) (2, 3)
- B. (0, 1) (0, 1) (0, 1) (0, 1)
- C. (0, 1) (1, 2) (0, 0) (2, 3)
- D. (0, 1) (0, 1) (0, 0) (0, 1)
Correct answer: D. (0, 1) (0, 1) (0, 0) (0, 1)
Both defaults are created once, but they are used differently. seen[name] = … mutates the shared dict, so it remembers names across calls. order = order + [name] builds a NEW list and rebinds only the local name; the default list stays [] forever. So every new name gets index len([]) = 0 and the local length 1; the repeat call for 'a' skips the if and sees the untouched default, length 0: (0, 1) (0, 1) (0, 0) (0, 1). The option with indices 0, 1, 2 would be right had the code used order.append(name).
More Python Programming questions
- What is printed? python def bucket(x, w): return x // w, x % w, int(x / w), -(-x // w) print(bucket(-7, 3), bucket(7, -3))
- What is printed? python d = {"b": 1, "a": 2, "c": 3} d["a"] = 9 d.update(b=7, d=4) d["c"] = d.pop("c") d.setdefault("a", 0) e = {d, "b"…
- What is printed? python a = [1, 2]; b = a; c = a[:] t = (a, c) a += [3] b = b + [4] c = 2 print(t[0] is a, b is a, t[1] is c, len(t[0])…
- What is printed? python a = list(range(8)) b = a[::2] a[1::2] = b[::-1] a[2:5] = [] del a[-2:] b[0] = 99 print(a, b)
- What is printed? python class Meter: unit = "m" def init(self): self.dict["v"] = 1 def getattr(self, name): return name.upper() def…
- What is printed? python def counter(): n = 0 def inc(k=1): nonlocal n n += k return n return inc c1, c2 = counter(), counter() g = (c1(i)…