Sarvesh waran
Sarvesh waran

Reputation: 21

For Loop - Range - Python - Question on the increment logic

I am trying to convert the below for loop to Python.

for (i = 5; i < n; i = i*5):

I am not sure how to make use of the Range function when i want the i value to be set to the multiple of 5. For example, 1st time I want the i to be 5, then followed by 25, then followed by 125 and it should go on.

The following is what i have tried:

i = 5 
for i in range (i, n+1, i*5)

The problem with the above being, the value of i getting incremented by 25, making it to 30 whereas i want the i to be 25 in the second iteration. It is pretty easy when using the while loop. But I am seeing if there is a way to implement the same in the for loop. Please help. Thanks in advance.

Upvotes: 2

Views: 413

Answers (4)

Frank Yellin
Frank Yellin

Reputation: 11330

Most Python programmers would just use a while loop:

i = 5
while i < n: 
    ....
    i = i * 5

If you really, really want a for loop:

import itertools
for i in itertools.takewhile(lambda x: x < n, (5 ** i for i in itertools.count(1))):
    ... whatever ...

Upvotes: 0

DYZ
DYZ

Reputation: 57135

There is a theorem in computer science that states that any "C-style" for loop can be transformed into an equivalent while loop. This is one of those cases where the transformation is desirable:

i = 5
while i < n:
   # Loop body goes here
    i *= 5

You can hide the loop logic behind a generator:

def multrange(start, stop, ratstep):
    i = start
    while i < stop:
        yield i
        i *= ratstep

list(multrange(5, 10000, 5))
#[5, 25, 125, 625, 3125]

Upvotes: 1

Red
Red

Reputation: 27577

You can define your own range function using yield!

def range(i, j, k):
    while i * k < j:
        i *= k
        yield i


for i in range(5, 2000, 5):
    print(i)

Output:

25
125
625

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61643

I am not sure how to make use of the Range function when i want the i value to be set to the multiple of 5

It will not work that way. range can only create arithmetic sequences; multiplying every time creates a geometric sequence.

What you can do is take advantage of the fact that the i values are successive powers of 5; so make a loop over the desired exponent values, and compute i inside the loop:

# Computing the `limit` in terms of `n` is left as an exercise.
# Just in case you were already computing `n` in terms of an existing `limit`,
# in which case you could just use it directly ;)
for j in range(limit):
    i = 5**j

Upvotes: 1

Related Questions