首页 > 编程语言 > 详细

python 实现bitmap,排序

时间:2018-09-18 16:48:31      阅读:171      评论:0      收藏:0      [点我收藏+]
#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,排序

原文:https://www.cnblogs.com/butter-007/p/9669708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!