For loop iterate over powers of 2

14,974

Solution 1

counter = 2

while counter <= 1024:
    print counter
    counter *= 2

Solution 2

You can use a generator expression so that it generates the numbers as needed and they don't waste memory:

>>> for x in (2**p for p in range(1, 11)):
...    print(x)

2
4
8
16
32
64
128
256
512
1024

In Python 2, you can use xrange instead of range to keep it as a generator and avoid creating unnecessary lists.

If you want to enter the actual stop point instead of the power to stop at, this is probably the simplest way:

from itertools import count
for x in (2**p for p in count(1)):
    if x > 1024:
        break
    print(x)

You could put it all in one line:

from itertools import count, takewhile
for x in takewhile(lambda x: x <= 1024, (2**p for p in count(1))):
    print(x)

but that's becoming silly (and not very readable).

Solution 3

You'll need to create your own function:

def doubling_range(start, stop):
    while start < stop:
        yield start
        start <<= 1

This uses a left-shift operation; you could also use start *= 2 if you find that clearer.

Demo:

>>> def doubling_range(start, stop):
...     while start < stop:
...         yield start
...         start <<= 1
... 
>>> for i in doubling_range(2, 1025):
...     print i
... 
2
4
8
16
32
64
128
256
512
1024

Solution 4

You say you want to iterate over the powers of 2 for each loop,

Seeing your example, the formulation could be:

Make a loop that multiply the initial by 2 untill it reach 1024.

ii = 2
while ii <= 1024: 
    print(ii)
    ii = ii*2
Share:
14,974
Minon Weerasinghe
Author by

Minon Weerasinghe

Updated on August 28, 2022

Comments

  • Minon Weerasinghe
    Minon Weerasinghe over 1 year

    I want to write a for loop that will iterate over the powers of 2 for each loop.

    For example I would want a range like this:

    2, 4, 8, 16, ... , 1024
    

    How could I do this?

    • Philip
      Philip over 8 years
      There are plenty of good information about how to do this at the web. Start with the basics of python. I will guarantee you that you will stumble upon for loops and how to do this if you just read some documentation/tutorial about python
    • TigerhawkT3
      TigerhawkT3 over 8 years
      Have you tried using Google, or reading your textbook, or anything at all on your own?
    • TigerhawkT3
      TigerhawkT3 over 8 years
      I could also ask how "2, 4, 8, 16" is a range of multiples of 2, or why there's no code or research effort here...
    • orangepips
      orangepips over 6 years
      Googling "iterate over powers of two" has this as the first result. And, other links thereafter on Google are actually worse. smh for a reasonable question.
  • SuperBiasedMan
    SuperBiasedMan over 8 years
    Please explain what your code does and why it will solve the problem. An answer that just contains code (even if it's working) usually wont help the OP to understand their problem.
  • Vishal
    Vishal over 8 years
    @SuperBiasedMan there is nothing to explain here. Isn't it straight forward answer?
  • SuperBiasedMan
    SuperBiasedMan over 8 years
    It's not very complicated, but the OP clearly didn't understand it if they needed to ask the question. And an explanation would make this a better answer.
  • João dos Reis
    João dos Reis over 8 years
    @Vishal the question is also very straightforward, so I'd say it's still needed, assuming we consider the question to be a valid one!
  • TigerhawkT3
    TigerhawkT3 over 8 years
    Sorry, but I can't think of any way for an answer to what's basically "how do I add two numbers together" (start <<= 1 looks cool, but it's equivalent to start = start + start) to be helpful to anyone who's spent more than a few minutes with the Python interpreter.
  • Martijn Pieters
    Martijn Pieters over 8 years
    @TigerhawkT3: Sorry you found this to be unhelpful; yup, the question is basic, and they probably got confused with a for loop rather than use a while loop. I'd hoped you judged answers on their own, separate from the quality of the question, however, it is what I do at any rate.
  • TigerhawkT3
    TigerhawkT3 over 8 years
    As I said, the answer to such a question is not helpful, in my opinion - not even to the OP, who will probably come back tomorrow to collect the code and not learn anything.
  • Martijn Pieters
    Martijn Pieters almost 8 years
    This only differs from answer in that you range up to the square root of the limit, where my answer ranges up to the limit itself. A different use-case. The OP didn't specify if they wanted to range up to 2**N (your approach) or to up to K (my approach). If run on Python 3, this is exactly the same thing that AndrewSmiley posted however.
  • Martijn Pieters
    Martijn Pieters almost 8 years
    Since you use print, you appear to be using Python 2. Using range() and map() on Python 2 means you produce lists up-front. range() produces a list with all the integers from 0 to floor(squareroot(N)), and then map() produces another list of integers, each a power of two. Only then do you iterate over those numbers. Only in Python 3 do range() and map() produce the numbers on demand.
  • endolith
    endolith almost 8 years
    @MartijnPieters None of the other answers uses a generator expression, which is what I'm illustrating. It's simple and efficient
  • Martijn Pieters
    Martijn Pieters almost 8 years
    But it is no more efficient than using a generator; mine doesn't require you to calculate the squareroot of the desired end value however.
  • endolith
    endolith almost 8 years
    @MartijnPieters Yes it's not more efficient, but it's simpler. It's not a square root, it's a logarithm. Yes, it becomes unreasonably complicated if you want to be able to enter stop point directly.
  • Martijn Pieters
    Martijn Pieters almost 8 years
    Ick, yes, I meant the log2.