范围内无限生成整数,步长

问题描述 投票:0回答:1

我需要无限的生成器,例如:

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

对于如下输入: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 我想要: 31, 63, 95, 127, 159, 191, 223, 255, 260, 228, 196 ... 从 0 开始计数,即使步长较小(参见 255、260),也包括 max_val,然后减去整步...当我们接近 0 时,情况相同。即...51、19、0、31

python iterator generator
1个回答
0
投票

你的代码几乎没问题,你只需要稍微改变一下语句的顺序:

def zigzag_iterator(current_value, step, max_val):
    direction = 1
    while True:
        current_value += step * direction
        if current_value >= max_val:
            current_value = max_val
            direction = -1
        elif current_value <= 0:
            current_value = 0
            direction = 1
        yield current_value
© www.soinside.com 2019 - 2024. All rights reserved.