if number is 1-2, 4 or 6-8 or 12-28, 30, 32...
John Machin
sjmachin at lexicon.net
Tue Jun 11 10:01:10 EDT 2002
Gustaf Liljegren <gustafl at algonet.se> wrote in message news:<Xns9229EE722467Fgustafl at 195.100.94.182>...
> I'm making a function that takes one integer and returns a boolean that
> says if the integer matches a number in a certain group of numbers. This
> group consists of single numbers aswell as ranges spanning thousands of
> numbers. I'm looking for an elegant way to write this function.
>
Here's another approach:
=== code =============================
# assume non-negative integers ...
ranges = ((1,2), (4,4), (6,8), (12, 28), (30,30), (32,132))
def load_map(r):
"""Load the bitmap"""
bigi = 0L
for lo, hi in r:
nbits = hi + 1 - lo
mask = (1L << nbits) - 1
bigi |= mask << lo
return bigi
def gustaf(x, bitmap):
"""Return 1 if x is in the bitmap, otherwise 0"""
return (bitmap & (1L << x)) != 0L
def try_it():
bmap = load_map(ranges)
for lo, hi in ranges:
print "testing interval", lo, hi
previ = -1
for i in (lo-1, lo, lo+1, (lo+hi)//2, hi-1, hi, hi+1):
if i > previ:
previ = i
print gustaf(i, bmap), i
if __name__ == "__main__":
try_it()
=== output ================================
testing interval 1 2
0 0
1 1
1 2
0 3
testing interval 4 4
0 3
1 4
0 5
testing interval 6 8
0 5
1 6
1 7
1 8
0 9
testing interval 12 28
0 11
1 12
1 13
1 20
1 27
1 28
0 29
testing interval 30 30
0 29
1 30
0 31
testing interval 32 132
0 31
1 32
1 33
1 82
1 131
1 132
0 133
=== bot bait ================================
bignum, long, fast, speed, optimize snot out of
Is the function elegant enough?
Cheers,
John
More information about the Python-list
mailing list