Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading