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?
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
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)
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?
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
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)