码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现bitmap,排序

时间:2018-09-18 17:20:19      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:python   整数   array   排序   []   math   __name__   默认   ceil   

#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,排序

标签:python   整数   array   排序   []   math   __name__   默认   ceil   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!