user6034362
user6034362

Reputation:

For with multiple in step python

in java I can use this folowing for :

for(int i = 1 ; i<=100 ; i*=2)

now , can we implement this type of loop with python for ?

something like this : for i in range(0,101,i*2)

Upvotes: 0

Views: 1933

Answers (4)

akash maurya
akash maurya

Reputation: 656

Instead of for loop, it is better to use while loop for multiple increments

i = 0
while (i < 350):
    print(i)
    i *= 5 // multiply value = 5

Upvotes: 0

Nidhi Ranjan
Nidhi Ranjan

Reputation: 33

from math import log counter=int(log(100,2)) for x in (2**y for y in range(1, counter+1)): print(x)

Hope this helps!

Upvotes: 0

Dan D.
Dan D.

Reputation: 74645

That loop meant to be over the powers of 2 less than 100. As noted starting with 0 would result in no progress.

>>> import math
>>> math.log(100)/math.log(2)
6.643856189774725
>>> 2**6
64
>>> 2**7
128
>>> int(math.log(100)/math.log(2))
6

This tells us that we can stop at 6 or int(math.log(100)/math.log(2)), range requires us to add one to include 6:

import math

for i in (2**p for p in range(int(math.log(100)/math.log(2))+1)):

An example run:

>>> for i in (2**p for p in range(int(math.log(100)/math.log(2))+1)):
...     print i
... 
1
2
4
8
16
32
64

The literal translation of for(int i = 1 ; i<=100 ; i*=2) is:

i = 1
while i <= 100:
    # body here
    i *= 2

This can be turned into an generator:

def powers():
    i = 1
    while i <= 100:
        yield i
        i *= 2

which can be used like:

for i in powers():
    print i

Upvotes: 2

dsboger
dsboger

Reputation: 496

You could define you own generator, like follows:

def pow2_range(max):
    i = 1
    while i < max:
        yield i
        i = i * 2

for x in pow2_range(100):
    print(i)

That would print:

1
2
4
8
16
32
64

Upvotes: 1

Related Questions