I am working on a problem, where I want to get all permutations, but am not permitted to modify the print statement. I am also not permitted to use itertools
or other packages.
Instuctions:
In order for the program to list out all possible routes it needs some work. Fix the program by adding an if statement that checks that the route includes all of the ports. In other words, check that each of the numbers 0, 1, 2, 3, 4 are included in the list route. Note that it isn't necessary to check that no port appears twice because if that were the case, then the route couldn't include all the five ports.
You do not need to change the print statement.
This is my code, but it doesn't work. How can this be fixed?
def main():
portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
# don't change this bit - provided in exercise
port1 = 0
for port2 in range(1, 5):
for port3 in range(1, 5):
for port4 in range(1, 5):
for port5 in range(1, 5):
route = [port1, port2, port3, port4, port5]
# instructions to add if statement that checks that the route includes all of the ports
# if "PAN" in route and "AMS" in route and "CAS" in route and "NYC" in route and "HEL" in route:
if all([val in route for val in portnames]):
# do not modify the print statement
print(' '.join([portnames[i] for i in route]))
else:
continue
main()
Adding the following print
statement before the if
condition shows the error:
# code before
print(route)
if all([val in route for val in portnames]):
# code after
# Output:
# [0, 4, 3, 2, 2]
# [0, 4, 3, 2, 3]
# [0, 4, 3, 2, 4]
# ...
route
is made up of integers generated by range
. You can instead make your if
statement:
if all([portnames.index(val) in route for val in 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