Trying to follow the Scipy documentation to apply the linear_sum_assignment function to my code, in which I’m trying to assign 1 robot to each pizza so that the total travel time of the robots is as small as possible.
Robots is a list of 6 robot objects of which I am purposely ignoring the first robot.
SwapTargets is a list of 5 Pizza objects
newlist = []
for j in range(1,len(Robots)):
for i in range(0,len(SwapTargets)):
ref_x = SwapTargets[i].coordinates[0]
ref_y = SwapTargets[i].coordinates[1]
value = ((ref_x - Robots[j].x)**2) + (ref_y - Robots[j].y)**2
newlist.append(value)
myarray = np.array(newlist).reshape(len(Robots[1:]),len(SwapTargets))
from scipy.optimize import linear_sum_assignment
row_ind, col_ind = linear_sum_assignment(myarray)
PizzaList = np.array([SwapTargets])[row_ind]
RobotList = np.array([Robots[1:]])[col_ind]
result = dict(zip(PizzaList, RobotList))
print(result)
At PizzaList = np.array([SwapTargets])[row_ind]
I’m getting an error IndexError: index 1 is out of bounds for axis 0 with size 1
Just as a test, If I replace [SwapTargets] with ["A,"B","C","D","E"] in PizzaList = np.array([SwapTargets])[row_ind] in I pull no error, but dont understand why my list of 5 objects does not work.
Thx from a python noobie
>Solution :
You are almost answering your own question. You state that SwapTargets is a list of 5 Pizza objects. This means that it could have been initialized like this:
SwapTargets = [pizza0, pizza1, pizza2, pizza3, pizza4, pizza5]
Then you say that while executing:
PizzaList = np.array(["A", "B", "C", "D", "E"])[row_ind]
works, executing
PizzaList = np.array([SwapTargets])[row_ind]
does not. To understand what’s going on, simply substitute the initialization of SwapTargets for the identifier, the above becomes:
PizzaList = np.array([[pizza0, pizza1, pizza2, pizza3, pizza4, pizza5]])[row_ind]
See the double nested brackets?
What’s happening here is that you are calling np.array() on a list of just one item (that item itself is a list of 5 items). In the successful call, you were calling the same function of a list of 5 items, which is probably what you want.
What you wanted to write was actually:
PizzaList = np.array(SwapTargets)[row_ind]
(no brackets around the argument).