## Problem 5: Remainder Generator Like functions, generators can also be higher-order. For this problem, we will be writing `remainders_generator`, which yields a series of generator objects. `remainders_generator` takes in an integer `m`, and yields `m` different generators. The first generator is a generator of multiples of `m`, i.e. numbers where the remainder is 0. The second is a generator of natural numbers with remainder 1 when divided by `m`. The last generator yields natural numbers with remainder `m - 1` when divided by `m`. Note that different generators should not influence each other. > Hint: Consider defining an inner generator function. Each yielded generator varies only in that the elements of each generator have a particular remainder when divided by m. What does that tell you about the argument(s) that the inner function should take in? ```python def remainders_generator(m): """ Yields m generators. The ith yielded generator yields natural numbers whose remainder is i when divided by m. >>> import types >>> [isinstance(gen, types.GeneratorType) for gen in remainders_generator(5)] [True, True, True, True, True] >>> remainders_four = remainders_generator(4) >>> for i in range(4): ... print("First 3 natural numbers with remainder {0} when divided by 4:".format(i)) ... gen = next(remainders_four) ... for _ in range(3): ... print(next(gen)) First 3 natural numbers with remainder 0 when divided by 4: 4 8 12 First 3 natural numbers with remainder 1 when divided by 4: 1 5 9 First 3 natural numbers with remainder 2 when divided by 4: 2 6 10 First 3 natural numbers with remainder 3 when divided by 4: 3 7 11 """ "*** YOUR CODE HERE ***" ``` Note that if you have implemented this correctly, each of the generators yielded by `remainder_generator` will be infinite - you can keep calling next on them forever without running into a `StopIteration` exception.
时间: 2024-02-14 15:04:40 浏览: 201
可以考虑在 `remainders_generator` 函数内部定义一个生成器函数,根据不同的余数来生成不同的生成器。具体实现如下:
```python
def remainders_generator(m):
"""
Yields m generators. The ith yielded generator yields natural numbers whose
remainder is i when divided by m.
"""
def gen_func(remainder):
"""
Generates natural numbers with remainder `remainder` when divided by m.
"""
n = remainder
while True:
yield n
n += m
for i in range(m):
yield gen_func(i)
```
在这个实现中,`remainders_generator` 函数内部定义了一个生成器函数 `gen_func`,它接收一个参数 `remainder`,表示生成的数值应该满足的余数。`gen_func` 中使用了一个无限循环,每次生成 `n`,然后将其加上 `m`,生成下一个数值,并不断重复这个过程。
`remainders_generator` 函数中使用一个循环来生成 `m` 个生成器,每个生成器使用 `gen_func` 来生成满足不同余数的数值。这样,`remainders_generator` 函数就能够生成 `m` 个无限的生成器,分别生成满足不同余数的自然数序列。
你可以运行代码,检查输出结果是否正确。注意,每个生成器都是无限的,可以连续调用 `next` 函数。
阅读全文