Is it possible to loop with a variable jump?

1

I wonder if it's possible to create a variable jump loop. For example, in the odd cycles the jump would be 2 and in even cycles the cycles would be 4.

I tried to do it with the tertiary operator of Python a if True else b , but it does not work because the range function does not change during the loop.

for j in range(i, len(message), small if odd else big):
    print(j)
    
asked by anonymous 20.10.2014 / 10:16

2 answers

4

You can toggle the step at the time of using the variable:

for j in range(1, 20, 3):
    print(j if j & 1 else j + 1)

Output:

1
5
7
11
13
17
19

See working at IDEONE .


If you want to adjust the moment that the steps occur, you can change the j + 1 by j - 1 , or change the + 1 on the if side, or even change the initial offset, goes from case concrete.

    
20.10.2014 / 10:56
3

Bacco's answer seems to me to be the only correct way, although some details escape me. Its sequence is:

         {  i,          se n == 0;
seq(n) = {  seq(n-1)+2, se n % 2 == 1;
         {  seq(n-1)+4, se n % 2 == 0.

That is, i , i+2 , i+6 , i+8 , i+12 , ... This sequence can be simplified to:

i + 0*3 - 0,
i + 1*3 - 1,
i + 2*3 - 0,
i + 3*3 - 1,
i + 4*3 - 0,
...

Where each term, then, is equal to i + n*3 - n%2 . i.e. "go from 3 to 3, subtracting 1 from the odd terms". One way to implement this would be:

for j in [i + n*3 - n%2 for n in range(0, limite_superior)]:
    print(j)

Where limite_superior is n , such that i + n*3 - n%2 >= len(message) , i.e.:

n*3 - n%2 >= len(message) - i
n*3 >= len(message) - i + n%2
n >= (len(message) - i + n%2)/3

But Bacco's solution is simpler and more elegant - just pay attention to the difference between% s and even% s (in one case the first deviation will be i , the other will be 2 ). >     

20.10.2014 / 11:17