自己实现:好丑啊
class BitMap():
def __init__(self, max):
self.size = self.calculate_index(max)
self.array = [0 for i in range(self.size + 1)]
def calculate_index(self, num):
return (num//31)
def calculate_elem(self, num):
return (num%31)
def insert_bit(self, num):
index = self.calculate_index(num)
elem = self.calculate_elem(num)
now_index = self.array[index]
self.array[index] = now_index | (1<<elem)
def test_bit(self, num):
index = self.calculate_index(num)
elem = self.calculate_elem(num)
if self.array[index] & (1<<elem):
return True
return False
def sort(self):
list1 = []
for i in range(self.size + 1):
if self.array[i]:
x = bin(self.array[i])[::-1]
n = len(str(x))
print(x, n)
for j in range(n-2):
print(x[j])
if x[j] == '1':
list1.append(j+(2**5-1)*i)
print(list1)
self.array = list1
def delete_bit(self, num):
if self.test_bit(num):
print(num)
index = self.calculate_index(num)
elem = self.calculate_elem(num)
print(self.array[index], elem)
self.array[index] = self.array[index] & (~(1<<elem))
suffle_array = [45, 2, 78, 35, 67, 90, 879, 0, 340, 123, 46]
max = 879
b = BitMap(max)
for num in suffle_array:
# print(num)
b.insert_bit(num)
print(b.array)
# c = b.test_bit(15)
# print(c)
b.delete_bit(35)
print(b.array)
抄袭版本:
#!/usr/bin/env python
#coding: utf8
# class Bitmap(object):
# def __init__(self, max):
# self.size = self.calcElemIndex(max, True)
# self.array = [0 for i in range(self.size)]
# def calcElemIndex(self, num, up=False):
# '''up为True则为向上取整, 否则为向下取整'''
# if up:
# return int((num + 31 - 1) / 31) #向上取整
# return int(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)
# def clean(self, i):
# elemIndex = self.calcElemIndex(i)
# byteIndex = self.calcBitIndex(i)
# elem = self.array[elemIndex]
# self.array[elemIndex] = elem & (~(1 << byteIndex))
# def test(self, i):
# elemIndex = self.calcElemIndex(i)
# byteIndex = self.calcBitIndex(i)
# if self.array[elemIndex] & (1 << byteIndex):
# return True
# return False
# if __name__ == '__main__':
# MAX = 879
# suffle_array = [45, 2, 78, 35, 67, 90, 879, 0, 340, 123, 46]
# result = []
# from ipdb import set_trace
# set_trace()
# bitmap = Bitmap(MAX)
# for num in suffle_array:
# print(bitmap.array)
# print(num)
# bitmap.set(num)
# for i in range(MAX + 1):
# if bitmap.test(i):
# result.append(i)
# print('原始数组为: %s' % suffle_array)
# print('排序后的数组为: %s' % result)