0
votes

I want to write a function that takes a list (in this case, the names of the ports) and prints out all the possible orderings of them. The order in which the permutations are printed doesn't matter, but they should all begin with Panama (PAN).

So far I got to the point to print out all permutations, however, I always fail to print out only those combinations that starts with PAN. Any ideas on how/where to change my code?

import itertools

portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
 
def permutations(route, ports):
    # write the recursive function here
    # remember to print out the route as the recursion ends
    sum = route + ports
    perms = list(itertools.permutations(sum))
    for perm in perms:
        output = []
        for item in perm:
            output.append(portnames[item])
        
        print(output)

# this will start the recursion with 0 as the first stop
permutations([0], list(range(1, len(portnames))))
1
Kindly add the expected output also for more answers - tbhaxor
Why not just add "PAN" to the beginning and just add permutations of everything else to that. - ssp

1 Answers

0
votes

You can remove the starting port (route in your code) from the list of portnames, and then get all the permutations of the remaining values. Then simply prepend the starting port to each of those permutations:

import itertools

portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
 
def permutations(route, ports):
    ports.remove(route)
    perms = itertools.permutations(ports)
    for perm in perms:
        output = [route] + list(perm)
        print(output)

# this will start the route with 'PAN' as the first stop
permutations('PAN', portnames)

Output:

['PAN', 'AMS', 'CAS', 'NYC', 'HEL']
['PAN', 'AMS', 'CAS', 'HEL', 'NYC']
['PAN', 'AMS', 'NYC', 'CAS', 'HEL']
['PAN', 'AMS', 'NYC', 'HEL', 'CAS']
['PAN', 'AMS', 'HEL', 'CAS', 'NYC']
['PAN', 'AMS', 'HEL', 'NYC', 'CAS']
['PAN', 'CAS', 'AMS', 'NYC', 'HEL']
['PAN', 'CAS', 'AMS', 'HEL', 'NYC']
['PAN', 'CAS', 'NYC', 'AMS', 'HEL']
['PAN', 'CAS', 'NYC', 'HEL', 'AMS']
['PAN', 'CAS', 'HEL', 'AMS', 'NYC']
['PAN', 'CAS', 'HEL', 'NYC', 'AMS']
['PAN', 'NYC', 'AMS', 'CAS', 'HEL']
['PAN', 'NYC', 'AMS', 'HEL', 'CAS']
['PAN', 'NYC', 'CAS', 'AMS', 'HEL']
['PAN', 'NYC', 'CAS', 'HEL', 'AMS']
['PAN', 'NYC', 'HEL', 'AMS', 'CAS']
['PAN', 'NYC', 'HEL', 'CAS', 'AMS']
['PAN', 'HEL', 'AMS', 'CAS', 'NYC']
['PAN', 'HEL', 'AMS', 'NYC', 'CAS']
['PAN', 'HEL', 'CAS', 'AMS', 'NYC']
['PAN', 'HEL', 'CAS', 'NYC', 'AMS']
['PAN', 'HEL', 'NYC', 'AMS', 'CAS']
['PAN', 'HEL', 'NYC', 'CAS', 'AMS']