Question: USE PYTHON3, DO NOT IMPORT PACKAGES Note: Please be careful and make sure it's correct, others keep messing up. Please do not overcomplicate and try
USE PYTHON3, DO NOT IMPORT PACKAGES
Note: Please be careful and make sure it's correct, others keep messing up. Please do not overcomplicate and try to keep it simple.
Given a positive integer k and three iterable objects, write a generator that, in each round, yields the next k elements from each iterable object in order, and repeats such rounds. (This algorithm is also known as Round Robin Scheduling.)
Note that the generator yields None if the iterable object cannot be iterated upon anymore. For example, when k is 4, but the iterator object only has 2 elements left, the iterator will yield None twice after yielding the remaining elements to fill in this gap.
Example:
>>> arg1 = "abcdefgh"
>>> arg2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arg3 = (True, False, True, False, True, False)
>>> gen = round_robin_generator(2, arg1, arg2, arg3)
If we keep calling next(gen), the output values will be:
'a', 'b', 1, 2, True, False, 'c', 'd', 3, 4, True, False,
'e', 'f', 5, 6, True, False, 'g', 'h', 7, 8, None, None,
In the first round, the function outputs two elements from each iterator ('a' and 'b' from the first iterator, 1 and 2 from the second iterator, and True and False from the third iterator). The function repeats such rounds twice. In the fourth round, when the function tries to output the next two elements from the third iterator, it fails because all six elements from the third iterator have been output in the first three rounds, so it yields None to fill in this gap.
Hints:
-
An infinite loop ("while True") may help to repeat our rounds indefinitely.
-
The next() function takes an optional second argument (called default), which specifies what value to return if the iterator reaches the end (has no more elements).
def round_robin_generator(k, arg1, arg2, arg3):
"""
>>> arg1 = "abcdefgh"
>>> arg2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arg3 = (True, False, True, False, True, False)
>>> gen = round_robin_generator(2, arg1, arg2, arg3)
>>> [next(gen, None) for _ in range(14)]
['a', 'b', 1, 2, True, False, 'c', 'd', 3, 4, True, False, \
'e', 'f']
>>> gen = round_robin_generator(3, arg1, arg2, arg3)
>>> [next(gen, None) for _ in range(14)]
['a', 'b', 'c', 1, 2, 3, True, False, True, 'd', 'e', 'f', 4, 5]
>>> arg4 = "dsc"
>>> arg5 = [2, 0]
>>> arg6 = "fall"
>>> gen = round_robin_generator(4, arg4, arg5, arg6)
>>> [next(gen, None) for _ in range(10)]
['d', 's', 'c', None, 2, 0, None, None, 'f', 'a']
"""
# YOUR CODE GOES HERE #
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
