-1

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)
Python_bug
  • 25
  • 6

1 Answers1

3

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)
Hugh Mungus
  • 382
  • 1
  • 7
  • The answer is no, since I am very new to python, I tend to make such simple mistakes! – Python_bug Jul 10 '22 at 14:46
  • How much faster is the generator version? – Kelly Bundy Jul 10 '22 at 14:48
  • 1
    @KellyBundy ok for the given input it's slower but for longer lists it is a few % faster. actually I think it depends on python version previously on 3.8, on 3.10 they're the same – Hugh Mungus Jul 10 '22 at 14:52
  • How fast is `math.dist` in comparison? – Kelly Bundy Jul 10 '22 at 14:59
  • @KellyBundy it is an order of magnitude faster – Hugh Mungus Jul 10 '22 at 15:03
  • Ok, that all agrees with my own benchmarks. The "Roughly equivalent to" code in the [doc](https://docs.python.org/3/library/math.html#math.dist) is btw also significantly faster, apparently squaring by 2.0 is faster (though could lose precision if the sum gets big). – Kelly Bundy Jul 10 '22 at 15:10
  • And storing each difference in a variable and multiplying it with itself instead of squaring is even faster (but still far slower than `math.dist`). – Kelly Bundy Jul 10 '22 at 15:14