How to Calculate Manhattan Distance in Python?

By Shivang Yadav Last updated : November 21, 2023

Manhattan Distance

Manhattan distance is a metric used to measure the distance between two vector points in a space. In Python, you can calculate the Manhattan distance between two points using the following formula:

Manhattan Distance = ∑|xi - yi|

Here, i is the ith element of each vector.

The calculation of Manhattan Distance in the 2-dimensional dataset is referred to as city block distance or taxi cab distance. This is used to measure the distance between two points in a grid-like structure.

Calculation of Manhattan Distance in Python

Manhattan's distance can be calculated using a directly creating a custom function that uses the above-mentioned formula for calculation. The code to calculate is,

Python Program to Calculate Manhattan Distance

# Python program to calculate Manhattan distance
from math import sqrt

def manhattanDist(a, b):
    return sum(abs(val1 - val2) for val1, val2 in zip(a, b))

A = [1, 1, 1, 1]
B = [5, 2, 4, 8]

print("Vector A", A)
print("Vector B", B)
print("Manhattans Distance : ", manhattanDist(A, B))

Output

The output of the above program is:

Vector A [1, 1, 1, 1]
Vector B [5, 2, 4, 8]
Manhattans Distance :  15

Another Approach: Using the citybook() method

Alternate method to calculate Manhattan distance in Python is citybook() method. Python provides a built-in method called cityblock() method present in the scipy package that performs that task for us.

Syntax

citybook(vectorA, vectorB)

Example: Python program to calculate Manhattan distance using citybook() method

# Python program to calculate Manhattan distance
from scipy.spatial.distance import cityblock

A = [1, 1, 1, 1]
B = [5, 2, 4, 8]

print("Vector A", A)
print("Vector B", B)

print("Manhattans Distance : ", cityblock(A, B))

Output

The output of the above program is:

Vector A [1, 1, 1, 1]
Vector B [5, 2, 4, 8]
Manhattans Distance :  15

Python SciPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.