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.
JavaScript
x
10
10
1
lst_a=[1,2,3,4,5]
2
lst_b=[1,2,4,5,8]
3
4
def distance(lst_a, lst_b):
5
sum_of = 0
6
for x, y in zip(lst_a, lst_b):
7
ans = (x - y)**2
8
sum_of += ans
9
return (sum_of)**(1/2)
10
Advertisement
Answer
Have you called the function?
JavaScript
1
2
1
distance(lst_a, lst_b)
2
Output:
JavaScript
1
2
1
3.3166247903554
2
For longer lists, you can also do this faster by summing a generator expression instead:
JavaScript
1
3
1
def distance(lst_a, lst_b):
2
return sum((x-y)**2 for x, y in zip(lst_a, lst_b))**0.5
3
Or you could use math.dist
(as pointed out in comments) which is significantly faster still:
JavaScript
1
4
1
import math
2
def distance(lst_a, lst_b):
3
return math.dist(lst_a, lst_b)
4