Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Complete the implementation of the function k _ tsp _ mtz _ encoding ( n , k , cost _ matrix ) below using PULP.
Complete the implementation of the function ktspmtzencodingn k costmatrix below using PULP. It follows the same input convention as the code supplied in the notes. The input n denotes the size of the graph with vertices labeled n k is the number of salespeople, and costmatrix is a list of lists wherein costmatrixij is the edge cost to go from i to j for i j Your code must avoid accessing costmatrixii to avoid bugs. These entries will be supplied as None in the test cases.
Your code must return a list lst that has exactly k
lists in it wherein lstj represents the locations visited by the jth
salesperson.
For the example above, for k
your code must return
For the example above, for k
your code must return
from pulp import
def ktspmtzencodingn k costmatrix:
# check inputs are OK
assert k n
assert lencostmatrix n f'Cost matrix is not nxn
assert alllencj n for cj in costmatrix f'Cost matrix is not nxn
prob LpProblemkTSP LpMinimize
# finish your implementation here
# your code must return a list of klists i il jjl wherein
# the ith entry in our list of lists represents the
# tour undertaken by the ith salesperson
# your code here
raise NotImplementedError
Test case:
costmatrixNone
None,
None,
None,
None
n
k
alltours ktspmtzencodingn k costmatrix
printfYour code returned tours: alltours
assert lenalltours k fkk must yield two tours your code returns lenalltours tours instead'
tourcost
for tour in alltours:
assert tour 'Each salesperson tour must start from vertex
i
for j in tour::
tourcost costmatrixij
i j
tourcost costmatrixi
printfTour cost obtained by your code: tourcost
assert abstourcost f'Expected tour cost is your code returned tourcost
for i in range n:
isintour if i in tour else for tour in alltours
assert sumisintour f vertex i is in sumisintour tours this is incorrect'
Please run above test case
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started