Python range function: increase step by multiplication of a number

Viewed 33

In C++, it can be written inside a for loop:

for(int i = 1; i < n; i++)
{
    for(int j = i; j <= n; j = j*7)    // increase j multiplication of 7
    {    
        // codes goes here
    }
}

but how to increase step by multiplication of a number in range() function in Python?

1 Answers

range only does linear ranges. There are a number of things you could do.

You could use a while loop:

for i in range(1, n):
   j = i
   while j <= n:
      # code goes here
      j *= 7

If you want to use this kind of loop multiple times, you could write a generators:

def mul_range(start, stop, multiple):
    value = start
    while value < stop: # using < for consistency with range
        yield value
        value *= multiple

...

for i in range(1, n):
    for j in mul_range(i, n + 1, 7):
        ... # code here
Related