Laser
Laser

Reputation: 33

Calculating Euclidean Distance 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 which give me two lists with numbers. My task is to calculate the euclidean distance with the given lists. However, I am not getting the right results. I am instead getting 3.7416573867739413, 3.0, 2.0 and 2.0. This is what I have so far, and I am not sure what I am doing wrong.

Upvotes: 3

Views: 2816

Answers (1)

user2285236
user2285236

Reputation:

The problem is here:

   for x in alist:
      for y in blist:

So for each point in alist, you are visiting all points in blist. For example, for alist = [1, 2, 3] and blist = [4, 5, 6], this loop would generate pairs (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6) But what you want to do is to look at only (1, 4), (2, 5), (3, 6). This can be achieved with the zip function. If you iterate over zip(alist, blist), it will iterate over those points. You can confirm this by executing

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

So if you change the nested loops with a single loop over zip, it will calculate the correct distance.

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

Upvotes: 5

Related Questions