R.Chen
R.Chen

Reputation: 11

How to loop through list of cities to calculate distances between them

I'm working on a brain teaser where I want to calculate all of the possible distances between 4 cities. I wrote a function where you can input the x and y coordinates of the two cities and it'll calculate the distance between them.

While I can individually call the function 6 times, that seems inefficient if the data set gets bigger. I think I should be using nested "for loops" but I can't figure out a way to properly increment the inner loop.

My initial idea was to create a list of object and use that in inner loop.

import math #Imports the math module

def calc_euclidean(x1,y1,x2,y2): #Function takes 4 arguments
    xDistancesqrd=math.pow((x2-x1),2) #x2-x1 squared
    yDistancesqrd=math.pow((y2-y1),2) #y2-y1 squared
    euclideanDistance=math.sqrt(xDistancesqrd+yDistancesqrd) #distance=square root (x2-x1)^2+(y2-y1)^2
    return euclideanDistance #Returns the result of the calculation, the euclidean distance between the points.

Budapest=[47.4979, 19.0402]
Vienna=[48.210033, 16.363449]
Sofia=[42.6977, 23.3219]
Zagreb=[45.8150, 15.9819]

cities=[Budapest,Vienna,Sofia,Zagreb]

Upvotes: 1

Views: 457

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49812

Use itertools.combinations() like:

Code:

for c1, c2 in it.combinations(cities, 2):
    print(c1, c2, calc_euclidean(c1[0], c1[1], c2[0], c2[1]))

Test Code:

import math  # Imports the math module
import itertools as it


def calc_euclidean(x1, y1, x2, y2):  # Function takes 4 arguments
    xDistancesqrd = math.pow((x2 - x1), 2)  # x2-x1 squared
    yDistancesqrd = math.pow((y2 - y1), 2)  # y2-y1 squared
    euclideanDistance = math.sqrt(
        xDistancesqrd + yDistancesqrd)  # distance=square root (x2-x1)^2+(y2-y1)^2
    return euclideanDistance  # Returns the result of the calculation, the euclidean distance between the points.


Budapest = [47.4979, 19.0402]
Vienna = [48.210033, 16.363449]
Sofia = [42.6977, 23.3219]
Zagreb = [45.8150, 15.9819]

cities = [Budapest, Vienna, Sofia, Zagreb]
for c1, c2 in it.combinations(cities, 2):
    print(c1, c2, calc_euclidean(c1[0], c1[1], c2[0], c2[1]))

Results:

[47.4979, 19.0402] [48.210033, 16.363449] 2.769860885620431
[47.4979, 19.0402] [42.6977, 23.3219] 6.432330443159777
[47.4979, 19.0402] [45.815, 15.9819] 3.4907522541710128
[48.210033, 16.363449] [42.6977, 23.3219] 8.877266213327731
[48.210033, 16.363449] [45.815, 15.9819] 2.4252345681376934
[42.6977, 23.3219] [45.815, 15.9819] 7.974531916670721

Upvotes: 1

Related Questions