數據結構中很特別的bitmap,bitmap原理:python3中一個帶符號的整數是8位,第一位是符號位,剩下63位可以按位操作。
用於不重複整數的排序,排序原理是:從文件讀取數組,按照數字大小在對應bit位置操作置1,時間複雜度是O(n)。遍歷對應位置,爲1就證明有數,以此排序。
參考原文,我是64位系統,python2和3的有符號整數都是8字節。所以略有修改。
如有錯誤,歡迎留言指導。
#!/home/wjl/anaconda3/bin/python
#coding:utf-8
import sys
byte= sys.getsizeof([1]) - sys.getsizeof([])
print("帶符號整數的字節數", byte)
class Bitmap(object):
"""帶符號的整數可以操作後63位"""
num_of_bit = byte * 8 - 1
def __init__(self, max):
self.size = self.calcElemIndex(max, True)
self.array = [0 for i in range(self.size)]
# cal the num of block element(8byte, 63bit to use)
def calcElemIndex(self, num, up=False):
'''up爲True則爲向上取整, 否則爲向下取整'''
if up:
return int((num + 63- 1) / 63) #向上取整
return num // 63
# cal the index of block element
def calcBitIndex(self, num):
return num % 63
# set 1
def set(self, num):
elemIndex = self.calcElemIndex(num)
byteIndex = self.calcBitIndex(num)
print(elemIndex, byteIndex)
elem = self.array[elemIndex]
# 位操作
self.array[elemIndex] = elem | (1 << byteIndex)
# set 0
def clean(self, i):
elemIndex = self.calcElemIndex(i)
byteIndex = self.calcBitIndex(i)
print(elemIndex, byteIndex)
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 = []
bitmap = Bitmap(MAX)
for num in suffle_array:
bitmap.set(num)
for i in range(MAX + 1):
if bitmap.test(i):
result.append(i)
print('原始數組爲: %s' % suffle_array)
print('排序後的數組爲: %s' % result)