ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def f(x, acc={}):
acc[x] = len(acc)
return acc
a = f("p")
b = f("q", {})
c = f("r")
print(a is c, a, b)- A. True {'p': 0, 'r': 1} {'q': 0}
- B. False {'p': 0} {'q': 0}
- C. True {'p': 0, 'q': 1, 'r': 2} {'q': 1}
- D. True {'p': 0, 'r': 2} {'q': 0}
Correct answer: A. True {'p': 0, 'r': 1} {'q': 0}
The default dict is created once when def runs. Calls 1 and 3 share it (so a is c, holding p:0 then r:1), while call 2 used its own fresh dict.
More Python Programming questions
- What is printed? python def f(n, seen=[]): if n in seen: return seen seen = seen + [n] return seen print(f(1), f(2), f(1))
- What is printed? python import time def stamp(t=[]): t.append(len(t)) return t print(stamp(), stamp(), stamp.defaults)
- What is printed? python x = 5 def f(a, b=x 2, , c=x): return a + b + c x = 100 print(f(1), f(1, c=x))
- What is printed? python def f(a, L=None): if L is None: L = [] L.append(a) return L r = f(1) print(f(2, r), f(3), r)
- What is printed? python class Cart: def init(self, items=[]): self.items = items a = Cart(); b = Cart(); c = Cart([])…
- What is printed? python fs = [] for i in range(3): fs.append(lambda x: x + i) i = 10 print([f(1) for f in fs])