Answer to Question #181646 in Python for Moanabelia

Question #181646

Write a Python program that solves the travelling salesperson problem.


Sample output:

Input: cost for every path:

Cost from 1-2: 10

Cost from 1-3: 15

Cost from 1-4: 20

Cost from 2-3: 35

Cost from 2-4: 25

Cost from 3-4: 30


Output:

Optimal Route: 12431

Total Path Cost: 80




1
Expert's answer
2021-04-15T10:14:49-0400
route = list(str(input("Enter optimal route: ")))
cost = 0
for i in range(1,len(route)):
    if route[i-1] == "1" and route[i] == "2" or route[i-1] == "2" and route[i] == "1":
        cost += 10
    elif route[i-1] == "1" and route[i] == "3" or route[i-1] == "3" and route[i] == "1":
        cost += 15
    elif route[i-1] == "1" and route[i] == "4" or route[i-1] == "4" and route[i] == "1":
        cost += 20
    elif route[i-1] == "2" and route[i] == "3" or route[i-1] == "3" and route[i] == "2":
        cost += 35
    elif route[i - 1] == "2" and route[i] == "4" or route[i - 1] == "4" and route[i] == "2":
        cost += 25
    elif route[i - 1] == "3" and route[i] == "4" or route[i - 1] == "4" and route[i] == "3":
        cost += 30
print(cost)


















Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS