Answer to Question #288552 in Python for Chetan

Question #288552

Calculate Euclidean distances between these pairs of points (total 10*10 = 100 pairs


including 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-19T12:47:40-0500
import math

def distance(p1, p2):
    """
    Calculate Eucidian distance between two points p1 and p2
    """
    return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)

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("{:.2f}".format(x), 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