ProgrammingVery hardCodeforces-style · placement coding round
What is printed?
What is printed?
calls = 0
def expensive():
global calls
calls += 1
return 0
d = {'x': 5}
for k in ['x', 'y', 'x']:
v = d.get(k, expensive())
print(v, calls)- A. 5 3
- B. 0 3
- C. 5 2
- D. 5 0
Correct answer: A. 5 3
The default argument of get is evaluated before the call, so expensive() runs on all three iterations even when the key exists. The last value found is 5.
More Python Programming questions
- What is printed? python d = {'a': 1, 'b': 2, 'c': 3} try: for k in d: if d[k] == 2: del d[k] except RuntimeError: print('error')…
- What is printed? python a = [1, 2, 2, 3, 4] for x in a: if x == 2: a.remove(x) print(a)
- What is printed? python it = iter(range(7)) print(list(zip(it, it)), list(it))
- What is printed? python print(sum([0.1] 10) == 1.0, sum([0.1] 10), round(sum([0.1] 10), 2))
- What is printed? python x = (5) y = (5,) print(type(x).name, type(y).name, len(y), ((5),) == (5,))
- What is printed? python a = {1, 2, 3} b = {3, 4} print(a ^ b, a.issubset({1, 2, 3, 4}), sorted(a - b, reverse=True), b > {3})