Framester
Framester

Reputation: 35521

Can you use bit shift operations in a 'for-loop'?

I have the following C for loop using bit shifts, that I want to reimplement in python.

n = 64
for(int stride = n>>1; stride >0; stride >>=1)
   {...

So wow would this loop look in python?

I know that n>>1 stands for division by 2, but I find it hard to model that with range().

Upvotes: 3

Views: 7219

Answers (8)

johnsyweb
johnsyweb

Reputation: 141860

Amadan's answer is spot on.

If you use this pattern a lot, I'd extract this into a simple generator function to be reused in for-loops:

>>> def strider(n):
...     stride = n >> 1
...     while stride > 0:
...         yield stride
...         stride >>= 1
...
>>> for n in strider(64):
...     print n
...
32
16
8
4
2
1

Upvotes: 5

MAK
MAK

Reputation: 26586

First thing that comes to mind is:

while stride>0:
   # do your stuff
   stride>>=1

I don't think it is a good idea to try and use for-loops in this case. In Python for-loops work much like for-each loops in other languages. They act on sequences. Although we could easily turn the range of values for stride into a sequence, the while IMHO is a much simpler and more natural way of expressing the idea.

Upvotes: 1

Amadan
Amadan

Reputation: 198438

All for(;;) loops can be rewritten as while loops, and vice versa.

n = 64
stride = n >> 1
while stride > 0:
    # stuff
    stride >>= 1

EDITED to reflect the change in the original

Upvotes: 3

Daniel Kluev
Daniel Kluev

Reputation: 11315

Well, closest is to use itertools module:

>>> from itertools import takewhile, imap, count
>>> n = 64
>>> for i in takewhile(bool, imap(lambda x:n >> x, count(1))):
...     print i
... 
32
16
8
4
2
1

Upvotes: -2

Björn Pollex
Björn Pollex

Reputation: 76848

How about using a logarithm?

for i in range(int(math.log(n, 2)), -1, -1):
    # stride is 2**i

Upvotes: -1

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29727

Think simpler:

>>> n = 64
>>> while n:
...     print n
...     n = n >> 1
...
64
32
16
8
4
2
1

Upvotes: 5

Tugrul Ates
Tugrul Ates

Reputation: 9687

Since you do not have many iterations:

for stride in [32, 16, 8, 4, 2, 1, 0]:
  # ...

Upvotes: 0

Daniel
Daniel

Reputation: 1527

You could write your own generator for use in the for loop

Upvotes: 0

Related Questions