Calculate Manhattan distances between these pairs of points (total 10*10 = 100
pairs inlcuding self pairs).This should give you a 10*10 2-D array where each value
corresponds to the distance between a pair
def distance(p1, p2):
"""
Calculate Manhattan distance between two points p1 and p2
"""
return abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])
def pairs_distance(points):
"""
Calculate between all points pairs
"""
n = len(points) # number of points
D = [ [0]*n for i in range(n)]
for i in range(n):
for j in range(n):
D[i][j] = distance(points[i], points[j])
return D
def print_array(A):
"""
Print 2D-array
"""
for row in A:
for x in row:
print(f"{x:4.1f}", end=' ')
print()
points = [(1,1), (1,3), (2,4), (-1,2), (-3,2),
(0,0), (2,1), (1,-2), (3,1), (-1,-3)]
D = pairs_distance(points)
print_array(D)
Comments
Leave a comment