Answer to Question #288921 in Python for Aaaa

Question #288921

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

1
Expert's answer
2022-01-23T15:21:15-0500
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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS