0

I'm trying to run sample code for transportation problem in Jupyter book, but generate error
TypeError: list indices must be integers or slices, not str. What's problem here? How to solve it? Thanks!

    from pulp import *

# Creates a list of all the supply nodes
Warehouses = ["A","B"]

# Creates a dictionary for the number of units of supply for each supply node
supply = {"A": 1000,
        "B": 4000}

# Creates a list of all demand nodes
Bars = ["1", "2", "3", "4", "5"]

# Creates a dictionary for the number of units of demand for each demand node
demand = {"1": 500,
        "2": 900,
        "3": 1800,
        "4": 200,
        "5": 700}

costs = [   #Bars
        #1 2 3 4 5
         [2,4,5,2,1],#A  Warehouses
        [3,1,3,2,3] #B
         ]



# Creates the prob variable to contain the problem data
prob = LpProblem("Beer Distribution Problem", LpMinimize)

# Creates a list of tuples containing all the possible routes for transport
Routes = [(w,b) for w in Warehouses for b in Bars]

# A dictionary called route_vars is created to contain the referenced variables (the routes)
route_vars = LpVariable.dicts("Route",(Warehouses,Bars),0,None,LpInteger)


# The objective function is added to prob first
prob += lpSum([route_vars[w][b]*costs[w][b] for (w,b) in Routes]), "Sum of Transporting Costs"

# The supply maximum constraints are added to prob for each supply node (warehouse)
for w in Warehouses:
    prob += lpSum([route_vars[w][b] for b in Bars]) <= supply[w], "Sum of Products out of Warehouse %s"%w

# The demand minimum constraints are added to prob for each demand node (bar)
for b in Bars:
    prob += lpSum([route_vars[w][b] for w in Warehouses]) >= demand[b], "Sum of Products into Bars %s"%b

1 Answer 1

1

This is more of a basic Python question than a PuLP question.

w,b are strings. So in your code, you are evaluating costs['A']['1']. If you type this in, you see the same error message. To be able to use string indices, you need to use a dict instead of a list (array).

Solution: make costs a dict

One way to do this is:

 costs = {'A': {'1':2,'2':4,'3':5,'4':2,'5':1},
          'B': {'1':3,'2':1,'3':3,'4':2,'5':3}}
Sign up to request clarification or add additional context in comments.

1 Comment

This is old code which were written in pulp package on 2007. I tried to study optimization, and now it finally works, Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.