随笔 - 89  文章 - 118  trackbacks - 0
<2013年8月>
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

留言簿(16)

随笔分类(56)

随笔档案(89)

文章分类

推荐博客

搜索

  •  

最新随笔

最新评论

阅读排行榜

转自:http://blog.csdn.net/fuyangchang/article/details/5637464
wiki地址http://en.wikipedia.org/wiki/Hamming_distance

在信息领域,两个长度相等的字符串的海明距离是在相同位置上不同的字符的个数,也就是将一个字符串替换成另一个字符串需要的替换的次数。

例如:

  • "toned" and "roses" is 3.
  • 1011101 and 1001001 is 2.
  • 2173896 and 2233796 is 3.

对于二进制来说,海明距离的结果相当于 a XOR b 结果中1的个数。

python代码如下

 

def hamming_distance(s1, s2):

    assert len(s1) == len(s2)

    return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

 

print (hamming_distance("gdad","glas"))

结果是2

 

C语言代码如下

 

unsigned hamdist(unsigned x, unsigned y)

{

  unsigned dist = 0, val = x ^ y;

 

  // Count the number of set bits

  while(val)

  {

    ++dist;

    val &= val - 1;

  }

 

  return dist;

}

 

int main()

{

         unsigned x="abcdcc";

         unsigned y="abccdd";

         unsigned z=hamdist(x,y);

         printf("%d",z);

}

posted on 2012-12-26 15:49 胡满超 阅读(562) 评论(0)  编辑 收藏 引用 所属分类: 算法转载

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理