I have the code below to calculate Euclidean Distance. however, my function does basically nothing. It gives no output and not even an error, it just runs and finishes.
lst_a=[1,2,3,4,5]
lst_b=[1,2,4,5,8]
def distance(lst_a, lst_b):
sum_of = 0
for x, y in zip(lst_a, lst_b):
ans = (x - y)**2
sum_of = ans
return (sum_of)**(1/2)
CodePudding user response:
Have you called the function?
distance(lst_a, lst_b)
Output:
3.3166247903554
For longer lists, you can also do this faster by summing a generator expression instead:
def distance(lst_a, lst_b):
return sum((x-y)**2 for x, y in zip(lst_a, lst_b))**0.5
Or you could use math.dist
(as pointed out in comments) which is significantly faster still:
import math
def distance(lst_a, lst_b):
return math.dist(lst_a, lst_b)