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)
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
[1 << k for k in range(0,7)] => [1, 2, 4, 8, 16, 32, 64]
for(int i = 0 ; i<=100 ; i*=2)would loop forever+=and posted a bogus answer. Deleted.