0

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)

4
  • 5
    for(int i = 0 ; i<=100 ; i*=2) would loop forever Commented May 29, 2017 at 1:42
  • I quickly misread that as += and posted a bogus answer. Deleted. Commented May 29, 2017 at 1:48
  • You can also pass a generator function as in this answer. Which I found to be cleaner and more flexible. Commented May 29, 2017 at 2:05
  • 1
    thank u very much @umutto , yes , u were right , that was very good Commented May 29, 2017 at 2:12

4 Answers 4

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

3 Comments

so for in python is not as powerful as for in java/C++ :(
@Mehdi.sf Python has a for-each loop. The other type of loop is basically a quick way to write a while-loop, which you can do in Python.
You can also use shifting integers: [1 << k for k in range(0,7)] => [1, 2, 4, 8, 16, 32, 64]
1

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

Comments

0

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!

Comments

0

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

Comments

Your Answer

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