Loop through list permutations and apply function to them

I am trying to get a permutation list of 5 airport entrances to go through the distance calculation and do the calculation for each permutation.

from airports import *
from math import *
import itertools

dicts=TravelLookUp()
dicts.dictAirport('airport.csv')
dicts.dictCurrency('countrycurrency.csv')
dicts.dictCurrencyRates('currencyrates.csv')

#print(airportdict.airportDict)
#airportdict.airportDict[] IS DICTIONARY

#print(test)

#print(AirportDict)
test= dicts.airportDict['DUB'].getLat()
print(test)

airportList=[]
airportHome=[]
airport1=input('Choose the first airport: ').upper()
airport2=input('Choose the second airport: ').upper()
airport3=input('Choose the third airport: ').upper()
airport4=input('Choose the fourth airport: ').upper()
airport5=input('Choose the fifth airport: ').upper()

airportHome=[airport1]
airportList=[airport2,airport3,airport4,airport5]

AirportCombinations = itertools.permutations(airportList,r=4)

def distance(airport1,airport2):
    distacnces=[]
    lat1=dicts.airportDict[airport1].getLat()
    long1=dicts.airportDict[airport1].getLong()
    lat2=dicts.airportDict[airport2].getLat()
    long2=dicts.airportDict[airport2].getLong()
    lat1R= (lat1*pi/180)
    long1R=(long1*pi/180)
    lat2R=(lat2*pi/180)
    long2R=(long2*pi/180)
    distance= acos(sin(lat1R)*sin(lat2R)*cos(long1R-long2R))*6373
    distances.append(distance)
    return distances

for i in AirportCombinations:
    i=list(i)
    route=[airportHome]
    for value in range(len(i)):
            route.append(value)
            totaldistance=0
            for i in range(len(route)-1):
                legcost=distance(route[i],route[i+1])
                totaldistance+=distance
                print(totaldistance)

distance()

      

The route list contains permutations and I want it to loop distance(airport1,airport2)

through the function for each pair of airports in each of the permutations.

Whenever I run this, it only calculates the distance between the same two airports 24 times, and what I want is to calculate the distance for each combination.

How do I calculate it to run all permutations using a function distance(airport1,airport2)

? And then create a list to store all of these calculations?

+3


source to share


2 answers


I think you are over complicating things in your loop by starting for i in AirportCombinations

.

I simplified this loop (and renamed your variables for clarity), but kept your method, that is, converted to a list for each route.

You also had a typo: I guess it totaldistance += distance

must be totaldistance += legcost

.

for sub_route in AirportCombinations:
    route = [airportHome] + list(sub_route)
    totaldistance = 0
    for i in range(len(route)-1):
        legcost = distance(route[i], route[i+1])
        totaldistance += legcost

    #I've un-indented this so it prints for each permutation
    print('route ' + str(route) + ' has distance ' + str(totaldistance)) 

    # Add the distance to a list or dictionary here if you want them available later...

      




Another method

You can get rid of the inner loop entirely, it leaves the reader to know which part of Zen of Python is more important - it is (better than nested), but does that "readability" trump ... "

The zip uses documentary behavior :

The iterator stops when it runs out of the shortest input iteration file

for sub_route in AirportCombinations:
    route = [airportHome] + list(sub_route)
    totaldistance = sum(distance(a[0], a[1]) for a in zip(route, route[1:]))        
    print('route ' + str(route) + ' has distance ' + str(totaldistance)) 

    # Add the distance to a list or dictionary here if you want them available later...

      

+2


source


I think your problem is here:

for i in AirportCombinations:
    i=list(i)
    route=[airportHome]        
    for value in range(len(i)): <<<
            route.append(value) <<<
            totaldistance=0
            for i in range(len(route)-1):
                legcost=distance(route[i],route[i+1])
                totaldistance+=distance
                print(totaldistance)

      

You add value

in route

when you should addi[value]



Or better yet, just go through i

directly:

for i in AirportCombinations:
    i=list(i)
    route=[airportHome]
    for value in i:
            route.append(value)
            totaldistance=0
            for i in range(len(route)-1):
                legcost=distance(route[i],route[i+1])
                totaldistance+=distance
                print(totaldistance)

      

PS - Using i

on two levels of a nested loop is just confusing ...

+1


source







All Articles