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.
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)
Comments
Leave a comment