Euclidean distance calculation with given lists

def distance(alist, blist):
    sum_of = 0
    for x in alist:
        for y in blist:
            ans = (x - y)**2
            sum_of += ans
    return (sum_of)**(1/2)
print(distance([1, 1, 3], [2, 2, 3])) #1.4142135623730951
print(distance([1, 2, 3], [2, 2, 3])) #1.0
print(distance([2, 2, 3], [2, 2, 3])) #0.0
print(distance([1, 1], [2, 2])) #1.4142135623730951

So, I have a set of test cases that give me two lists with numbers. My task is to calculate the Euclidean distance with these lists. However, I am not getting the right results. I get 3.7416573867739413, 3.0, 2.0, and 2.0 instead. This is what I still have, and I'm not sure what I'm doing wrong.

+4
source share
1 answer

The problem is here:

   for x in alist:
      for y in blist:

, alist blist. , alist = [1, 2, 3] blist = [4, 5, 6] (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6). , , - (1, 4), (2, 5), (3, 6). zip. zip(alist, blist), . ,

list(zip(alist, blist))
Out: [(1, 4), (2, 5), (3, 6)]

, zip, .

def distance(alist, blist):
    sum_of = 0
    for x, y in zip(alist, blist):
        ans = (x - y)**2
        sum_of += ans
    return (sum_of)**(1/2)


distance([1, 1, 3], [2, 2, 3])
Out: 1.4142135623730951
+4

Source: https://habr.com/ru/post/1663363/


All Articles