拉风的咖菲猫
pythonimport itertools
def bounce(interval):
"""Infinite bounce for specific range list."""
down = reversed(interval[1:-1])
return itertools.cycle(itertools.chain(interval, down))
# >>> list(itertools.islice(bounce(range(5)), 20))
# [0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3]
猛跑小猪
其实我想要的是从小到大,再从大到下,再从小到大,并不是直接重复的过程。
我后来自己想了一个实现
from itertools import cycle, chain
# Get a sequence like (0,1,2,3,2,1)
base_sequence = chain(range(n), range(n - 2, 0, -1))
for i in cycle(base_sequence):
# do something
if condition_satisfied:
break