ProgrammingVery hardCodeforces-style · placement coding round
What is printed?
What is printed?
calls = []
def f(x):
calls.append(x)
return x * 2
m = map(f, [1, 2, 3])
print(calls)
first = next(m)
print(calls, first)
print(list(m), calls)- A. [1, 2, 3] | [1] 2 | [4, 6] [1, 2, 3]
- B. [] | [1, 2] 2 | [4, 6] [1, 2]
- C. [] | [1] 2 | [4, 6] [1]
- D. [] | [1] 2 | [4, 6] [1, 2, 3]
Correct answer: D. [] | [1] 2 | [4, 6] [1, 2, 3]
map is lazy, so nothing runs until next is called. After one next only 1 has been processed, and list(m) consumes the rest. The calls list is one object, so the last print shows all three calls.
More Python Programming questions
- In Python, when is the outermost iterable of a generator expression such as (x for x in make()) evaluated?
- What is printed? python class Countdown: def init(self, n): self.n = n def iter(self): while self.n > 0: yield self.n self.n -= 2 c =…
- What is printed? python from itertools import permutations p = sorted(permutations('cab')) print([''.join(x) for x in p][3], len(p))
- What is printed? python print(() is (), [] is [], (1, 2) == (1, 2))
- A program must answer 10^5 range-sum queries over an array of 10^5 numbers in CPython. Which approach is fastest?
- What is printed? python from functools import lrucache class C: @lrucache(maxsize=None) def f(self, x): return x 2 a, b = C(), C() a.f(1)…