1

Can I count to 100, but reset every 10 back to 0 using bit masks? - or am I barking up the wrong tree?

"""
Required output:
1,2,3,4,5,6,7,8,9,0,1,2,3,4,5...etc repeated 10 times.
"""

reset = 10
for x in range(0, 101):
    a = (x ^ reset)
    b = x & a
    print "Value: %s, %s, %s" % (x, a, b)
Chris
  • 2,739
  • 4
  • 29
  • 57
  • 1
    Basically you're asking: how do I implement my own modulo function? – wvdz Apr 10 '14 at 15:44
  • ah, I think so yes, I think this might help me: http://stackoverflow.com/questions/11076216/re-implement-modulo-using-bit-shifts – Chris Apr 10 '14 at 16:02

3 Answers3

1

Use the mod operator, %:

for x in range(1, 101):
    a = x // 10
    b = x % 10
    print "Value: %s, %s, %s" % (x, a, b)
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1

This is not possible by applying a bit mask. This can be understood easily with the code example below, which prints the last four bits of the numbers 6,16,...,96. You can see that the bit patterns are different for each number, but for each goes x % 10 == 6.

So one way or another, you are going to have to evaluate the whole number.

for x in range(0,100):
    if x % 10 == 6:
        print (bin(x & 0xf))

result:

0b110
0b0
0b1010
0b100
0b1110
0b1000
0b10
0b1100
0b110
0b0
wvdz
  • 16,251
  • 4
  • 53
  • 90
0

If you want faster way, consider using itertools.cycle

Here is my experiment.

from itertools import *
def cycle_iter():
    for i in islice(cycle(xrange(10)), 0, 101):
        yield i

def cycle_mod():
    for x in xrange(0, 101):
        yield x % 10

def cycle_mask():
    for x in xrange(0, 101):
        yield x & 7 & 7#<--It does cycle as 012345670123... And last "& 7" means you need at least one or more operator to generate 01234567890123...

Test:

>>> %timeit x = list(cycle_iter())
100000 loops, best of 3: 9.07 us per loop

>>> %timeit x = list(cycle_mod())
100000 loops, best of 3: 10.2 us per loop

>>> %timeit x = list(cycle_mask())
100000 loops, best of 3: 10.9 us per loop
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43