Exercise: Python

Questions for: Generators

How does the itertools.filterfalse() function behave when used with a generator?
A:
It filters elements that evaluate to False in the generator
B:
It filters elements that evaluate to True in the generator
C:
It stops the generator after one iteration
D:
It interleaves values from different generators
Answer: A
itertools.filterfalse() filters elements in the generator that evaluate to False based on the provided function.
How does the generator.throw(StopIteration) method affect a running generator?
A:
It raises a StopIteration exception inside the generator
B:
It forcibly terminates the generator
C:
It has no effect on the running generator
D:
It restarts the generator from the beginning
Answer: B
generator.throw(StopIteration) forcibly terminates the running generator by raising a StopIteration exception.
What does the itertools.permutations() function do when used with a generator?
A:
It generates all possible permutations of the elements in the generator
B:
It returns a single permutation of the elements
C:
It stops the generator after one iteration
D:
It shuffles the values produced by the generator
Answer: A
itertools.permutations() generates all possible permutations of the elements in the generator.
How does the generator.send(value) method differ from next(generator) when used with a generator?
A:
They are equivalent in functionality
B:
generator.send(value) initializes the generator, while next(generator) retrieves the next value
C:
next(generator) can be used without a value, while generator.send(value) requires a value
D:
generator.send(value) returns the value sent, while next(generator) does not
Answer: C
next(generator) can be used without providing a value, while generator.send(value) requires a value to be sent into the generator.
How can you implement a generator that produces a sequence of powers of 2?
A:
Using a loop with a yield statement
B:
By calling a recursive function with yield
C:
Using a list comprehension with yield
D:
By using the itertools.cycle() function
Answer: A
A generator for a sequence of powers of 2 can be implemented using a loop with a yield statement.
Ad Slot (Above Pagination)
Quiz