Python 二进制中1的个数

使用py来统计二进制中1的个数

举例如下:(实现tanimoto相似度函数)

def  getOneNum(bits):
    countOne = 0
    while bits:
        countOne = countOne+1
        bits = bits&(bits-1)
    return float(countOne)
    

def tanimoto(X, Y):
    XYbits = X&Y
    return getOneNum(XYbits)/(getOneNum(X)+getOneNum(Y)-getOneNum(XYbits))

print(tanimoto(0b011010,0b100111))

关于更多使用非二进制数据来计算tanimoto等相似矩阵,可以参考:

https://e3fp.readthedocs.io/en/latest/_modules/e3fp/fingerprint/metrics.html#tanimoto

https://github.com/keiserlab/e3fp/blob/1.1/e3fp/fingerprint/metrics/array_metrics.py

猜你喜欢

转载自blog.csdn.net/weixin_42001089/article/details/89096235