For loop iterate over powers of 2

前端 未结 5 810
醉话见心
醉话见心 2021-01-28 16:55

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
         


        
5条回答
  •  余生分开走
    2021-01-28 17:37

    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
    

提交回复
热议问题