Hamming distance 定义和计算
汉明距离是使用在数据传输差错控制编码里面的,汉明距离是一个概念,它表示两个(相同长度)字符串对应位置的不同字符的数量,我们以d(x,y)表示两个字x,y之间的汉明距离。对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。
You are given two strings of equal length, you have to find the Hamming Distance between these string.
Where the Hamming distance between two strings of equal length is the number of positions at which the corresponding character is different.
Examples:
Input : str1[] = "geeksforgeeks", str2[] = "geeksandgeeks"
Output : 3
Explanation : The corresponding character mismatch are highlighted.
"geeksforgeeks" and "geeksandgeeks"
Input : str1[] = "1011101", str2[] = "1001001"
Output : 2
Explanation : The corresponding character mismatch are highlighted.
"1011101" and "1001001"
https://www.geeksforgeeks.org/concepts-of-hamming-distance/
Hamming Distance Problem: In general, it is assumed that it is more likely to have fewer errors than more errors. This “worst-case” approach to coding is intuitively appealing within itself. Nevertheless, it is closely connected to a simple probabilistic model where errors are introduced into the message independently for each symbol and with a fixed probability p < 1/2. In order to talk about the “number of errors” hamming distance is introduced.
Definition: The Hamming distance between two integers is the number of positions at which the corresponding bits are different. It is not dependent on the actual values of xi and yi but only if they are equal to each other or not equal.
Proposition: The function d is a metric. That is, for every x, y, z ∈ AN:
0 ≤ d(x, y) ≤ N
d(x, y) = 0 if and only if x = y
d(x, y) = d(y, x)
d(x, z) ≤ d(x, y) + d(y, z) (triangle inequality)
# Python3 program to find
# hamming distance b/w two
# string
# Function to calculate
# Hamming distance
def hammingDist(str1, str2):
i = 0
count = 0
while(i < len(str1)):
if(str1[i] != str2[i]):
count += 1
i += 1
return count
# Driver code
str1 = "geekspractice"
str2 = "nerdspractise"
# function call
print(hammingDist(str1, str2))
# This code is contributed by avanitrachhadiya2155
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~