2

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.

1
  • 1
    Unless you implement a custom iterable, you can't. Commented Nov 13, 2020 at 1:33

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

0

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

1 Comment

Please do not advise anyone to redefine built-in functions. Also, your function starts at a wrong nimber
0

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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.