4
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.

demongolem
  • 9,474
  • 36
  • 90
  • 105
Laser
  • 43
  • 1
  • 4

1 Answers1

5

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
ayhan
  • 70,170
  • 20
  • 182
  • 203
  • Oh okay, I see. If you don't mind explaining, what exactly does "zip" do? – Laser Dec 09 '16 at 19:50
  • 1
    zip(...) zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. – kvivek Dec 09 '16 at 19:52
  • 1
    @EliezerShahid you can always find out what a builtin or standard library function does by reading the documentation: [`zip()`](https://docs.python.org/3/library/functions.html#zip). – Zero Piraeus Dec 09 '16 at 19:55