ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def make_ops():
ops = {}
for name, sym in [("add", "+"), ("mul", "*")]:
ops[name] = eval(f"lambda a, b: a {sym} b")
return ops
ops = make_ops()
late = [lambda a, b: eval(f"a {s} b") for s in "+*"]
print(ops["add"](3, 4), ops["mul"](3, 4), late[0](3, 4))- A. 7 12 7
- B. 7 12 12
- C. 12 12 12
- D. 7 7 7
Correct answer: B. 7 12 12
eval builds each lambda's source with the symbol already substituted, so add and mul are fixed. The comprehension lambdas instead look up s only when called, after the loop ended with s = '*', so late[0] multiplies.
More Python Programming questions
- What is printed? python x = 1 def f(): return x def g(): x = 2 return f() def h(): global x x = 3 return f() print(g(), h(), f())
- What is printed? python class Celsius: def init(self, t=0): self.t = t def get(self, obj, owner): return self if obj is None else obj.c…
- What is printed? python class Vec: def init(self, c): self.c = c def mul(self, k): return Vec((x k for x in self.c)) rmul = mul def…
- What is printed? python class Ordered: def init(self, v): self.v = v def lt(self, o): print("lt", end=" ") return self.v < o.v def…
- What is printed? python import functools @functools.totalordering class V: def init(self, n): self.n = n def eq(self, o): return self.n ==…
- What is printed? python def f(): l = [] for i in range(3): try: if i == 0: raise ValueError l.append(i) except ValueError: l.append("v")…