Exercise 2 Advanced..."Type Error" on website. Code runs fine in PyCharm
I get a TypeError: 'type' object is not subscriptable on line 30 with the following code. Any help is appreciated. I also noticed the website’s interpreter never gives you the correct line when throwing an error
portnames = ["PAN", "AMS", "CAS", "NYC", "HEL"]
# https://sea-distances.org/
# nautical miles converted to km
D = [
[0,8943,8019,3652,10545],
[8943,0,2619,6317,2078],
[8019,2619,0,5836,4939],
[3652,6317,5836,0,7825],
[10545,2078,4939,7825,0]
]
# https://timeforchange.org/co2-emissions-shipping-goods
# assume 20g per km per metric ton (of pineapples)
co2 = 0.020
# DATA BLOCK ENDS
# these variables are initialised to nonsensical values
# your program should determine the correct values for them
def permutations(route: list[int], ports: list[int]) -> list[list[int]]:
if len(ports) < 1:
return [route]
else:
result: list[list[int]] = []
for i in range(len(ports)):
result.extend(permutations(route + [ports[i]], ports[:i] + ports[i + 1 :]))
return result
def shortest_path():
min_distance = float("inf")
best_route = []
for route in permutations([0], list(range(1, len(portnames)))):
d = D[route[0]][route[1]] + D[route[1]][route[2]] + D[route[2]][route[3]] + D[route[3]][route[4]]
if d < min_distance:
min_distance = d
best_route = route
return best_route, min_distance
def main():
# Do not edit any (global) variables using this function, as it will mess up the testing
# this will start the recursion
bestroute,smallest=shortest_path()
# print the best route and its emissions
print(' '.join([portnames[i] for i in bestroute]) + " %.1f kg" % smallest)
main()