ckdanny
2/27/2020 - 3:03 PM

pyBitSet

pyBitSet

import sys

class BitSet:
    def __init__(self, value=0):
        self.__collection = value

    @property
    def bit(self):
        return bin(self.__collection)[2:]

    @property
    def size(self):
        return sys.getsizeof(self.__collection)

    def value(self):
        return self.__collection

    def set(self, pos: int):
        self.__collection = self.__collection | (1 << pos)

    def unset(self, pos: int):
        self.__collection = self.__collection & ~(1 << pos)

    def reset(self):
        self.__collection = 0

    def exist(self, pos):
        return self.__collection & (1 << pos) != 0

    def count(self):
        return bin(self.__collection).count("1")

    def __repr__(self):
        return "{} bytes".format(self.size)


if __name__ == "__main__":
    bs = BitSet()
    bs.set(2)
    bs.set(3)
    bs.set(4)
    print("3 is marked: ", bs.exist(3))
    bs.unset(3)
    print(bs.value())
    print("3 is marked: ", bs.exist(3))
    print("4 is marked: ", bs.exist(4))
    print("99 is marked: ", bs.exist(99))
    print(bs.bit)
    print(bs.count())
    print(bs)