美文网首页
python3 求汉明距离

python3 求汉明距离

作者: fanchuang | 来源:发表于2019-05-10 09:19 被阅读0次

1. leetcode 461 求2个数字之间的汉明距离

这种写法其实的最好的:
return bin(x ^ y).count('1')

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        # 求出y的长度,然后再把x补充相应的长度。

        # 找出2个数中较大的数
        if x > y:
            x, y = y, x
       
        res = 0 
        
        m = bin(x)[2:]
        n = bin(y)[2:]
        l = len(n) 
        # print(m.zfill(l))
        # print(n)
 
        
        for i, j in zip(m.zfill(l), n):
            if i != j:
                res += 1
        # print(res)
        return res

2. 求2个相等长度的字符串之间的汉明距离

"""
# 计算韩明距离
# 所谓 汉明距离:
# 对于二进制字符串a与b来说,它等于a 异或b以后所得二进制字符串中“1”的个数。
# https://zh.wikipedia.org/wiki/%E6%B1%89%E6%98%8E%E8%B7%9D%E7%A6%BB
# 字符串--->阿斯卡 ---> binary value 

# [https://cryptopals.com/sets/1/challenges/6](https://cryptopals.com/sets/1/challenges/6)

"""

a = 'this is a test'
b = 'wokka wokka!!!'

def hamming(a, b):
    m = ''.join([format(ord(i), 'b').zfill(8) for i in a])
    n = ''.join([format(ord(i), 'b').zfill(8) for i in b])
    print(m)
    print(n)

    want = 0
    for r, t in zip(m, n):
        if r != t:
            want += 1
    print(want)
    return want     

hamming(a, b)     # 37 

相关文章

  • python3 求汉明距离

    1. leetcode 461 求2个数字之间的汉明距离 这种写法其实的最好的:return bin(x ^ y)...

  • leetcode D1 Hamming Distance

    leetcode.com/problems/hamming-distance/ 求汉明距离,首先通过x^y(一样的...

  • 汉明距离、超立方体、异或的一些知识

    汉明距离和汉明重量 汉明距离是以理查德·卫斯里·汉明的名字命名的。在信息论中,两个等长字符串之间的汉明距离是两个字...

  • LeetCode 461.汉明距离

    ?博客原文 :《LeetCode 461.汉明距离 - JavaScript》 汉明距离定义:两个整数之间的汉明距...

  • 汉明距离

  • 汉明距离

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 x 和 y,计算它们之间的汉明...

  • 汉明距离

    指的是两个(相同长度)字符串,你变成我,我变成你,需要换掉多少个字符的总和,即Max(Sum1,Sum2),比如...

  • 汉明距离

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/hamm...

  • 汉明距离

    https://zhuanlan.zhihu.com/p/94081111pHash简单来说,是通过感知哈希算法对...

  • 汉明距离

    题目: 题目的理解: 将整数转化为二进制,然后再转化为字符串,进行字符串比较,得到不同的位数。 python实现 ...

网友评论

      本文标题:python3 求汉明距离

      本文链接:https://www.haomeiwen.com/subject/ofkooqtx.html