Problem 2: Back and forth (100pts)
Problem
Implement
backAndForth, a generator which takes in an iteratortand yields elements fromtin multiple rounds.In round \( i \), where \(i\) is a positive integer,
backAndForth:
- yields consecutive \( i \) elements from
t, if \( i \) is odd,- skips consecutive \( i \) elements from
t, if \( i \) is even.
实现 backAndForth,它是一个生成器,接受一个迭代器 t 并在多轮中产出 t 中的元素。
在第 \( i \) 轮中,其中 \(i\) 是一个正整数,backAndForth:
- 如果 \( i \) 是奇数,则产出
t中连续的 \( i \) 个元素, - 如果 \( i \) 是偶数,则跳过
t中连续的 \( i \) 个元素。
def backAndForth(t):
"""Yields and skips elements from iterator t, back and forth.
>>> list(backAndForth(iter([1, 2, 3, 4, 5, 6, 7, 8, 9])))
[1, 4, 5, 6]
>>> list(backAndForth(iter([1, 2, 2])))
[1]
>>> # generators allow us to represent infinite sequences!!!
>>> def naturals():
... i = 0
... while True:
... yield i
... i += 1
>>> m = backAndForth(naturals())
>>> [next(m) for _ in range(9)]
[0, 3, 4, 5, 10, 11, 12, 13, 14]
"""
"*** YOUR CODE HERE ***"
Hints
- 每次
next后立刻yield,避免遗漏。
Solutions
使用 try:
注意不要一次性使用 i 次 next,这可能遗漏最后一次输出。
def backAndForth(t):
i = 1
while True:
try:
for j in range(i):
x = next(t)
if i % 2: yield x
i += 1
except StopIteration: return