Python Programming - Generators

Exercise : Generators - General Questions
  • Generators - General Questions
46.
What is the purpose of the itertools.product() function when used with generators?
It generates the Cartesian product of input iterables
It filters elements based on a specified condition
It stops the generator after one iteration
It interleaves values from different generators
Answer: Option
Explanation:
itertools.product() generates the Cartesian product of input iterables, creating tuples with all possible combinations of elements.

47.
How does the generator.throw(RuntimeError, "message") method affect a running generator?
It raises a custom exception inside the generator
It forcibly terminates the generator
It has no effect on the running generator
It restarts the generator from the beginning
Answer: Option
Explanation:
generator.throw(RuntimeError, "message") raises a custom exception of type RuntimeError with the specified message inside the generator.

48.
What happens if a generator function contains both yield and return statements?
It raises a GeneratorExit exception
It raises a StopIteration exception
It returns the specified value and stops the generator
It is a syntax error; yield and return cannot be used together
Answer: Option
Explanation:
If a generator function contains both yield and return statements, it returns the specified value and stops the generator.

49.
What is the purpose of the itertools.starmap() function when used with generators?
It applies a function to elements of the generator
It generates the sum of elements in the generator
It stops the generator after one iteration
It filters elements based on a specified condition
Answer: Option
Explanation:
itertools.starmap() applies a function to elements of the generator, using arguments unpacked from each tuple in the input iterable.

50.
How can you implement a generator that produces a Fibonacci sequence?
Using a loop with a yield statement and two variables
By calling a recursive function with yield
Using a list comprehension with yield
By using the itertools.cycle() function
Answer: Option
Explanation:
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.
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))