Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
66.
What is the purpose of the
itertools.accumulate() function when used with generators?
Answer: Option
Explanation:
itertools.accumulate() generates the cumulative sum of elements in the generator, creating an iterator that yields the accumulated results.
67.
How does the
itertools.islice() function differ from itertools.takewhile() when used with generators?
Answer: Option
Explanation:
itertools.islice() allows for arbitrary slicing by specifying start, stop, and step parameters, while itertools.takewhile() stops yielding elements when a specified condition becomes false.
import itertools
def my_generator():
for i in range(10):
yield i
sliced_iterable = itertools.islice(my_generator(), 2, 7)
takewhile_iterable = itertools.takewhile(lambda x: x < 5, my_generator())
print(list(sliced_iterable)) # Output: [2, 3, 4, 5, 6]
print(list(takewhile_iterable)) # Output: [0, 1, 2, 3, 4]
68.
How does the
generator.throw(StopIteration) method differ from raise StopIteration when used with a generator?
Answer: Option
Explanation:
generator.throw(StopIteration) is used to stop the generator and raise a StopIteration exception inside the generator. raise StopIteration is used outside the generator to signal the end of the iteration.
69.
What happens if a generator function contains a
return value statement followed by a yield statement?
Answer: Option
Explanation:
If a generator function contains both
return value and yield statements, it returns the specified value and stops the generator.
def my_generator():
return 42
yield # This statement is never reached
# Example usage
gen = my_generator()
result = next(gen, None)
print(result) # Output: 42
70.
What is the purpose of the
itertools.starmap() function when used with generators?
Answer: Option
Explanation:
itertools.starmap() applies a function to elements from a single generator, using argument unpacking to provide the function with multiple arguments.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers