Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
46.
What is the purpose of the
itertools.product()
function when used with 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?
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?
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?
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?
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))
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers