Home > Backend Development > Python Tutorial > How to implement a bitmap index in Python

How to implement a bitmap index in Python

PHPz
Release: 2023-05-16 21:49:10
forward
1019 people have browsed it

The code is as follows:

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 ) / 31) #向上取整
		return num / 31
		
	def calcBitIndex(self, num):
		return num % 31
		
	def set(self, num):
		elemIndex = int(self.calcElemIndex(num))
		byteIndex = self.calcBitIndex(num)
		elem      = self.array[elemIndex]
		self.array[elemIndex] = elem | (1 << byteIndex)	
		
	def clean(self, i):
		elemIndex = int(self.calcElemIndex(i))
		byteIndex = self.calcBitIndex(i)
		elem      = self.array[elemIndex]
		self.array[elemIndex] = elem & (~(1 << byteIndex))
	def test(self, i):
		elemIndex =int(self.calcElemIndex(i))
		byteIndex = self.calcBitIndex(i)
		if self.array[elemIndex] & (1 << byteIndex):
			return True
		return False
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)
Copy after login

The above is the detailed content of How to implement a bitmap index in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template