1. 程式人生 > >python 實現bitmap,排序

python 實現bitmap,排序

false bitmap turn print pen main sel 可用 其余

#python整數類型默認是有符號類型。可用位數是31位。


import math


class Bitmap(object):
def __init__(self, max):
self.size = math.ceil(max / 31)
self.array = [0 for i in range(self.size)]

def calcElemIndex(self, num):
return num // 31

def calcBitIndex(self, num):
return num % 31

def set(self, num):
elemIndex = self.calcElemIndex(num)
byteIndex = self.calcBitIndex(num)
elem = self.array[elemIndex]
self.array[elemIndex] = elem | (1 << byteIndex)
#左移相當於乘以2的次方

def clean(self, num):
elemIndex = self.bitmap.calcElemIndex(num)
byteIndex = self.bitmap.calcBitIndex(num)
elem = self.array[elemIndex]
self.array[elemIndex] = elem & (~(1 << byteIndex))#清除改位,不影響其余位

def test(self, num):
elemIndex = self.calcElemIndex(num)
byteIndex = self.calcBitIndex(num)
elem = self.array[elemIndex]
if elem & (1 << byteIndex)
:
return True
return False


if __name__ == ‘__main__‘:
# bitmap = Bitmap(90)
# print("需要%d個元素。" % bitmap.size)
# print("存儲在第%d個元素上的第%d位上面" % (bitmap.calcElemIndex(47), bitmap.calcBitIndex(47)))
max = 688
suffle_array = [0, 67, 1, 45, 187, 65, 58, 101, 33, 252, 688, 145, 254, 487]
result = []
bitmap = Bitmap(688)
for i in suffle_array:
bitmap.set(i)
for i in range(max + 1):
if bitmap.test(i):
result.append(i)
print(result)

python 實現bitmap,排序