Shuvendu Roy - 3 months ago 35

Python Question

What is equivalent to

`for (I=2; I<n; I*=2)`

in python.

I tried to do this with range() function and I know how it works with increment only. But here I want to multiply it in each iteration. I don't want to do it manually in side the loop

Answer

While `while`

is easy, `while`

is also slow. Try:

```
In [3]: import math
In [4]: n = 10
In [5]: for i in (2**n for n in range(1, int(math.log2(n)) + 1)):
...: print(i)
...:
2
4
8
In [6]: n = 40
In [7]: for i in (2**n for n in range(1, int(math.log2(n)) + 1)):
...: print(i)
...:
2
4
8
16
32
In [8]: n = 60
In [9]: for i in (2**n for n in range(1, int(math.log2(n)) + 1)):
...: print(i)
...:
2
4
8
16
32
In [10]: n = 100
In [11]: for i in (2**n for n in range(1, int(math.log2(n)) + 1)):
...: print(i)
...:
2
4
8
16
32
64
```