Python | Calculate City Block Distance
City block distance is generally calculated between 2-coordinates of a paired object. It is the summation of absolute difference between 2-coordinates. The city block distance of 2-points a and b with k dimension is mathematically calculated using below formula:
In this article two solution are explained for this problem – one with the Python code and the other one with the use of a predefined method.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
array1 = [1, 2, 13, 5]
array2 = [1, 27, 3, 4]
The CityBlock distance between 2 array is: 36
a = [34, 44, 89, 81, 67, 49, 33, 59]
b = [98, 34, 23, 12, 233, 23, 44]
The CityBlock distance between 2 array is: 412
Code: Python scratch code to calculate the distance using the above formula.
The CityBlock distance between 2 arrays is: 36
There is no restriction for the same size of arrays. So, it’s easy to calculate City Block distance between 2-coordinates using above formula but we can calculate the same using predefined method for arrays having 2-dimension or more.
Code: Python code using the predefined method to calculate the distance using the above formula.
[[ 36. 17.] [ 27. 16.]]