Home > Software engineering >  how to calculate distance between two points within the same list
how to calculate distance between two points within the same list

Time:11-03

I have a list named 'cords' with all the x-y coordinates in a list. List of x, y co-ordinates I need to calculate the distance between 1st(x,y) and 2nd(x,y) then 2nd(x,y) and 3rd(x,y) coordinates and so on until the end of the list. The values in the list are in float.

i am using

def find_distance():

    for i in range (0, (len(cords))):
        res = [float(ele) for ele in cords[i]]
        dis. append(res)
        for j in range (1, ((len(cords))-1)):
            dist=math.sqrt((cm.dis[i][0] - cm.dis[j][0])**2   (cm.dis[i][1] - cm.dis[j][1])**2)
            dista. append(dist)
 return res , dista

            

This throws an error that list index is out of range, how can i solve this?

CodePudding user response:

You should use zip as zip will iterate till exhaustion of any of the provided list

from math import sqrt
points = [(1,2.3), (3.4, 5.6), (2.3, 7.8)]
res = [ sqrt((y[0]-x[0])**2   (y[1]-x[1])**2) for x,y in zip(points, points[1:]) ]

CodePudding user response:

  1. let's say your i=0. now your "dis" has 1 element [x,y] and you initiated y to 1.
  2. Now you are doing this "cm.dis[i][0] - cm.dis[j][0])**2". here dis[j][0] or dis[1][0] doesn't exist
  3. all you have at this point is dis[0][1] and dis[0][1] as "dis" has one element [[x,y]]
  • Related