0

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

3
  • This is an infinite loop. 0 * 2 is 0. Commented Nov 21, 2016 at 17:25
  • Show your code,the error your getting and what result your expecting.That will help us on helping you. Commented Nov 21, 2016 at 17:29
  • this is syntax for java or c++ i want to do it in python Commented Nov 21, 2016 at 17:33

2 Answers 2

2

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

3 Comments

please consider, that 1/2 = 0 in python2, so 0.5 can be more general; plus n**(0.5) is not what you need here. You should use log2.
@quantummind again, you are absolutely correct. I've edited it one more time. It's been one of those mornings...
>>> import this ;)
1

Simple is the rule in python. While is easy:

n = 20
i = 2

while (i<n):
    print "the i variable is "+str(i)
    i = i * 2

I (originally, this has since been changed) used addition for this simple example, multiplication would simply use the "*" operator as you did.

3 Comments

The question says I*=2, which is multiplication, i = i + 2 in your answer is addition.
The comment notes that. Concept is being taught; I write real code for money.
OK, I would like to revoke down-vote, but I cannot do that until you edit your answer. Consider that you might do what the customer asked, instead of writing what you want, and tell him that he can modify it to work as he/she wanted. :-)

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.