Search code examples
pythonstructure

Storing a structure field into a vector


I have code that solves the assignment problem in Python using Google-OR Solver. Since I am new to Python, I need bit of help in storing variables in the usual vector form rather than the complicated structure-field form.

for i in range(0, assignment.NumNodes()):
    print('Worker %d assigned to task %d.  Cost = %d' % (i,assignment.RightMate(i), assignment.AssignmentCost(i)))

what i want to do this i just want the two arrays of 'Workers' and 'Task'. For workers It is obvious that it will be 0 to last one, but i also need the vector of indices of Tasks. How do I store this

'assignment.RightMate()' 

values in a single vector and print just those values


Solution

  • Using a list comprehension to get all values of assignment.RightMate()

    assignment_list = [assignment.RightMate(i) for i in range(assignment.NumNodes()]
    

    For workers you simply have:

    worker_list = list(range(assignment.NumNodes()))
    

    Explanation

    The list comprehension is equivalent to the following for loop (which is an alternative method of doing this):

    assignment_list = []
    for i in range(assignment.NumNodes()):
      assignment_list.append(assignment.RightMate(i))
    

    Note range() starts at 0 by default so:

    range(0, X) is equivalent to range(X)