Exercise: Python

Questions for: Generators

How can you implement a generator that produces a Fibonacci sequence?
A:
Using a loop with a yield statement and two variables
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 Fibonacci sequence can be implemented using a loop with a yield statement and two variables to keep track of the current and previous values. -PROGCODE-
def fibonacci_sequence():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Example usage
fibonacci_gen = fibonacci_sequence()
for _ in range(5):
    print(next(fibonacci_gen))
-PROGCODE-END-
What is the purpose of the itertools.starmap() function when used with generators?
A:
It applies a function to elements of the generator
B:
It generates the sum of elements in the generator
C:
It stops the generator after one iteration
D:
It filters elements based on a specified condition
Answer: A
itertools.starmap() applies a function to elements of the generator, using arguments unpacked from each tuple in the input iterable.
What happens if a generator function contains both yield and return statements?
A:
It raises a GeneratorExit exception
B:
It raises a StopIteration exception
C:
It returns the specified value and stops the generator
D:
It is a syntax error; yield and return cannot be used together
Answer: C
If a generator function contains both yield and return statements, it returns the specified value and stops the generator.
How does the generator.throw(RuntimeError, "message") method affect a running generator?
A:
It raises a custom 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: A
generator.throw(RuntimeError, "message") raises a custom exception of type RuntimeError with the specified message inside the generator.
What is the purpose of the itertools.product() function when used with generators?
A:
It generates the Cartesian product of input iterables
B:
It filters elements based on a specified condition
C:
It stops the generator after one iteration
D:
It interleaves values from different generators
Answer: A
itertools.product() generates the Cartesian product of input iterables, creating tuples with all possible combinations of elements.
Ad Slot (Above Pagination)
Quiz