Python Generators & Iteration Quiz
1. What will be the output? g = (x * 2 for x in range(5)) print(next(g)) print(next(g))
A. 0 then 2
B. 0 then 1
C. 2 then 4
D. 2 then 6
2. What will be the output? g = (x for x in range(6) if x % 2 == 1) print(next(g) + next(g))
A. 3
B. 4
C. 8
D. 6
3. What will be the output? g = (x + 1 for x in range(4)) print(list(g))
A. [1, 2, 3, 4]
B. [1, 2, 3]
C. [2, 3, 4, 5]
D. [0, 1, 2, 3]
4. What will be the output? g = (x for x in range(5)) print(next(g)) print(next(g)) print(list(g))
A. 0, 1, [2, 3, 4]
B. 1, 2, [3, 4]
C. 0, 1, [0, 1, 2, 3, 4]
D. 0, 2, [1, 3, 4]
5. What will be the output? g = (x * x for x in range(1, 6)) print(next(g) + next(g) + next(g))
A. 30
B. 9
C. 14
D. 16
1 comment:
Python Generators & Iteration
What will be the output?
g = (x * 2 for x in range(5))
print(next(g))
print(next(g))
The generator first produces 0 × 2 = 0 and then 1 × 2 = 2.
What will be the output?
g = (x for x in range(6) if x % 2 == 1)
print(next(g) + next(g))
The first two odd values are 1 and 3, and 1 + 3 equals 4.
What will be the output?
g = (x + 1 for x in range(4))
print(list(g))
The source values 0, 1, 2, 3 are each increased by 1, producing \[1, 2, 3, 4\].
What will be the output?
g = (x for x in range(5))
print(next(g))
print(next(g))
print(list(g))
The first two next() calls consume 0 and 1, leaving 2, 3, and 4 for list(g).
What will be the output?
g = (x * x for x in range(1, 6))
print(next(g) + next(g) + next(g))
The first three generated values are 1², 2², and 3², giving 1 + 4 + 9 = 14.
Post a Comment