ProgrammingHardTCS NQT pattern
What is printed?
What is printed?
counter = 0
def count_calls(f):
def wrapper(*a, **kw):
global counter
counter += 1
return f(*a, **kw)
return wrapper
@count_calls
def a1(): pass
@count_calls
def a2(): pass
a1(); a1(); a2()
print(counter)- A. 2
- B. 3
- C. 1
- D. 0
Correct answer: B. 3
Each decorated function shares the same module-level counter through the global statement. a1() runs twice and a2() runs once, so counter is incremented three times in total.
More Python Programming questions
- What is printed? python def applytwice(f): def wrapper(x): return f(f(x)) return wrapper @applytwice def inc(x): return x + 1 print(inc(5))
- What is printed? python def outerdeco(f): print("setup") def wrapper(a, kw): print("call") return f(a, kw) return wrapper @outerdeco def…
- What is printed? python def h(a, b, c): return a + b + c args = [1, 2, 3] print(h(args)) args2 = [1, 2] try: print(h(args2)) except…
- What is printed? python def k(a, , b): return a + b try: k(1, 2) except TypeError: print("TypeError") print(k(1, b=2))
- What is printed? python def n(kw): return kw print(n({"a": 1}, {"b": 2}))
- What is printed? python def p(a, b, c=3): return a, b, c d = {"a": 1, "b": 2, "c": 10} print(p(d))