Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

HW4 - ColumnDistances Write a python program to calculate the Euclidean Distance

ID: 3574119 • Letter: H

Question

HW4 - ColumnDistances Write a python program to calculate the Euclidean Distance between the columns of a matrix.The matrix data will be in a text file and all numbers will be integers.Matrix size is 6 rows by 5 columns. You can create a text file, Data.txt, and write numbers separated by tab ( ) or comma (,). Your program will open Data.txt file as input file, read the numbers and calculate the Euclidean Distance between the columns. The Euclidean Distance is defined as follows let x be column1 y be column2 Euclidean Distance d(x,y) = sqrt( (x1-y1)^2 + (x2-y2)^2 + (x3-y3)^2 + (x4-y4)^2 + (x5-y5)^2 ) Example x = [1,2,3,4,0]y = [0,2,3,2,2] Euclidean Distance d(x,y) = sqrt( (1-0)^2 + (2-2)^2 + (3-3)^2 + (4-2)^2 + (0-2)^2 ) = sqrt( 1 + 0 + 0 + 4 + 4) = 3.0 As output, your program will save the Euclidean distances into a file, ColumnDistances.txt.The numbers in the ColumnDistance.txt can be separated by tab ( ) or comma (,). The numbers in ColumnDistances.txt may be float type.You may use functions from other modules, like math or random as you need.You can define your own function to calculate the Euclidean Distance. Submit Data.txt ColumnDistances.txt Python Program Note : ColumnDistances.txt file will contain following distance values between columns {your ColumnDistance.txt file may have all distance values in the same column, or row} d(c1,c2),d(c1,c3),d(c1,c4),d(c1,c5) d(c2,c3),d(c2,c4),d(c2,c5) d(c3,c4),d(c3,c5) d(c4,c5)

Explanation / Answer

import math # importing math module for power function
def ed(l1,l2): # calculating eucledian distance for columns
sum=0;
sum=sum+math.pow((l1[0]-l2[0]),2) # formula for eucledian diatance
sum=sum+math.pow((l1[1]-l2[1]),2)
sum=sum+math.pow((l1[2]-l2[2]),2)
sum=sum+math.pow((l1[3]-l2[3]),2)
sum=sum+math.pow((l1[4]-l2[4]),2)
with open('ColumnDistances.txt', 'a') as f: # writing the result into file
f.write('%f' % sum)
f.write('%s' % " ")
with open('Data.txt') as f: # reading data from file
array = [[int(x) for x in line.split()] for line in f] # into an array
ed(array[0],array[1])
ed(array[1],array[3])
ed(array[4],array[5]