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))
  1. A. 7 12 7
  2. B. 7 12 12
  3. C. 12 12 12
  4. 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

Exams that ask this topic