ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def make_acc():
total = []
def add(x):
total.append(x)
return sum(total)
def reset():
nonlocal total
total = []
return add, reset
add, reset = make_acc()
add(5); add(5)
saved = add.__closure__[0].cell_contents
reset()
print(add(1), saved, add.__closure__[0].cell_contents)- A. 1 [5, 5] [1]
- B. 11 [5, 5, 1] [5, 5, 1]
- C. 1 [] [1]
- D. 11 [5, 5] [1]
Correct answer: A. 1 [5, 5] [1]
add and reset share the same cell for total. reset rebinds the cell to a new empty list, so add(1) returns 1. `saved` still references the old list object, which is not changed by the rebinding.
More Python Programming questions
- What is printed? python adders = [lambda x, n=n: x + n for n in range(3)] mults = list(map(lambda n: (lambda x: x n), range(3)))…
- What is printed? python def outer(): fs = [] for i in range(3): def f(j=None): return i if j is None else j fs.append(f) if i == 1: break…
- What is printed? python x = "global" def f(): return [x for in range(1)][0] def g(): x = "local" return (lambda: x)() def h(): return…
- What is printed? python try: r = [1 / x for x in [1, 0, 2]] except ZeroDivisionError: r = "partial?" g = (1 / x for x in [1, 0, 2]) out =…
- What is printed? python def f(x): if x > 0: return x print(f(1), f(-1), f(0) or "zero", f(2) and f(-2))
- What is printed? python print(repr([] or {} or 0 or ""), "a" and "b" or "c", "" and 1 or 0, not "0")