Calculating Hamming Distance Between Strings

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

The Hamming distance is a measure of the difference between two strings of equal length. In other words, it is the number of positions at which the corresponding symbols are different. In this challenge, you will be asked to write a function that calculates the Hamming distance between two values.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13650{{"`Calculating Hamming Distance Between Strings`"}} python/tuples -.-> lab-13650{{"`Calculating Hamming Distance Between Strings`"}} python/function_definition -.-> lab-13650{{"`Calculating Hamming Distance Between Strings`"}} python/build_in_functions -.-> lab-13650{{"`Calculating Hamming Distance Between Strings`"}} end

Hamming Distance

Write a function hamming_distance(a, b) that takes two integers as arguments and returns the Hamming distance between them. The function should perform the following steps:

  1. Use the XOR operator (^) to find the bit difference between the two numbers.
  2. Use bin() to convert the result to a binary string.
  3. Convert the string to a list and use count() of str class to count and return the number of 1s in it.
def hamming_distance(a, b):
  return bin(a ^ b).count('1')
hamming_distance(2, 3) ## 1

Summary

In this challenge, you have learned how to calculate the Hamming distance between two values using Python. The Hamming distance is a useful measure of the difference between two strings of equal length, and it has many applications in computer science and information theory.

Other Python Tutorials you may like