-1

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?

mraya99
  • 37
  • 5
  • You could help yourself by providing some *minimum* code about the question you have and get faster feedback. It's hard to just *describe* your problem w/o any code... "The code isn't too long"... right? – Daniel Hao Aug 30 '22 at 12:21
  • Maybe you should show the code you have? – AKX Aug 30 '22 at 12:21
  • If it is python >=3.10 you might want to look at "pattern matching", however without knowing your code or what exactly you want to achieve I cannot say if that would be helpful in your case or not. – Arbor Chaos Aug 30 '22 at 12:28
  • Sorry I realise I should be pasting my code in these questions so you all can provide more accurate advice. In saying that, thank you all for the advice anyway and thanks Tobias for that link. That's exactly what I was after. – mraya99 Aug 30 '22 at 12:33

2 Answers2

1

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
AKX
  • 152,115
  • 15
  • 115
  • 172
0

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)
hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51
  • 1
    This actually looks even better than the way I did it. I like how you defined the function outside of the while loop and just made a call to it. That will clean up my code. I also like the itertools.cycle() function above that other people have recommended, but thanks for your response. – mraya99 Aug 31 '22 at 13:02