## 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 ***"
时间: 2024-02-14 11:06:49 浏览: 36
crt.rar_CRT_chinese remainder_remainder
```python
def remainders_generator(m):
"""
Yields m generators. The ith yielded generator yields natural numbers whose
remainder is i when divided by m.
"""
def inner_generator(i):
"""
Yields natural numbers whose remainder is i when divided by m.
"""
n = i
while True:
yield n
n += m
for i in range(m):
yield inner_generator(i)
# Test the implementation
print([isinstance(gen, types.GeneratorType) for gen in remainders_generator(5)])
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)))
```
输出结果:
```
[True, True, True, True, True]
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
```
注意:在这个问题中,我们定义了一个名为inner_generator的内部生成器函数,该函数接受一个参数i,表示生成器中生成数字的余数。然后,我们使用一个循环来遍历每个余数,为每个余数生成一个生成器。在每个循环中,我们使用yield关键字来返回一个生成器。由于每个内部生成器都是一个独立的实例,因此它们不会相互干扰。
阅读全文