Is there a way to loop using staggered steps in python? (i.e. every odd step is 3, every even step is 4)

Question:

Currently, I’m using a while loop which interrupts once the total steps made have exceeded a certain limit. In each iteration of this loop I have a boolean which just switches between true and false, and depending on the value of the boolean, the step taken is either 3 or 4.

The code isn’t too long and it works well (for everything I’ve tested so far). I was just wondering if there was an even easier way of doing this? Does the range function somehow accommodate for this, or is there any function in python that does this?

Asked By: mraya99

||

Answers:

You can write a small generator using itertools.cycle():

from itertools import cycle


def stagger_step(value, *steps):
    for step in cycle(steps):
        yield value
        value += step


for i, value in enumerate(stagger_step(1, 3, 4), 1):
    print(i, value)
    if i == 10:
        break

This prints out

1 1
2 4
3 8
4 11
5 15
6 18
7 22
8 25
9 29
10 32
Answered By: AKX

I think the way you’re doing it is the best way. Just use a while loop. Simple and easy to understand.

def do_something_with_x(x):
    print(x)

x = 0
while x < 500:
    x += 3
    do_something_with_x(x)
    x += 4
    do_something_with_x(x)
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.