需求:实现符合特定边界规则的Python无限Zigzag迭代生成器
实现符合特定规则的Zigzag无限生成器
现有Zigzag迭代生成器函数如下,在小步长场景下可正常工作,但在大步长接近边界时无法满足需求:
def zigzag_iterator(current_value, step, max_val): direction = 1 while True: if current_value >= max_val: direction = -1 elif current_value <= 0: direction = 1 current_value += step * direction if direction == 1: current_value = min(current_value, max_val) else: current_value = max(0, current_value) yield current_value
比如输入g = zigzag_iterator(current_value=2, step=1, max_val=4)时,生成序列3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3...,符合“首个生成值为当前值的下一个”的要求,但输入current_value=0, step=32, max_val=260时,无法生成符合规则的目标序列。
需要满足的核心规则:
- 首个生成值为当前值的下一个;
- 正向接近max_val时,先返回max_val,再按完整步长反向生成;
- 反向接近0时,先返回0,再按完整步长正向生成。
实现代码
def zigzag_iterator(current_value, step, max_val): direction = 1 # 1表示正向递增,-1表示反向递减 while True: next_val = current_value + step * direction if direction == 1: # 处理正向逻辑 if next_val > max_val: # 先返回max_val,再切换反向 yield max_val direction = -1 current_value = max_val - step else: yield next_val current_value = next_val else: # 处理反向逻辑 if next_val < 0: # 先返回0,再切换正向 yield 0 direction = 1 current_value = 0 + step else: yield next_val current_value = next_val
验证示例
- 输入
g = zigzag_iterator(current_value=2, step=1, max_val=4),生成序列:3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3...,符合初始需求; - 输入
g = zigzag_iterator(current_value=0, step step=32, max_val=260),生成序列:32, 64, 96, 128, 160, 192, 224, 256, 260, 228, 196, ..., 32, 0, 32, ...,满足边界处理规则。
内容的提问来源于stack exchange,提问作者emcek
相关产品推荐
相关产品推荐

