You can download this code by clicking the button below.
This code is now available for download.
Calculates the Hamming distance between two equal-length strings, which is the number of positions at which the corresponding symbols are different.
Technology Stack : Uses the built-in function zip() to iterate over corresponding characters of the two strings and compare them for equality.
Code Type : Function
Code Difficulty : Intermediate
def get_hamming_distance(str1, str2):
"""Calculate the Hamming distance between two equal-length strings.
Args:
str1 (str): The first string to compare.
str2 (str): The second string to compare.
Returns:
int: The number of positions at which the corresponding symbols are different.
Raises:
ValueError: If the two strings are not of equal length.
"""
if len(str1) != len(str2):
raise ValueError("The two strings must be of equal length.")
distance = sum(ch1 != ch2 for ch1, ch2 in zip(str1, str2))
return distance