Mynameiswha
Mynameiswha

Reputation: 89

I'm trying to use the boolean variable in my optimization problem. It displays "IndexError: list index out of range"

What is wrong with my code or approach?

My optimization model's objective is to select the companies that are profitable given their cost and the profit they can make. Namely, the companies are A,B and C. Their respective costs are 2,1,1 and the profit they can generate are 3, 2, 3 respectively.

If I change the code companies=["A", "B", "C"] to companies = [0, 1, 2], the code works. But is there a way to use strings and get the desired result?

Here is my code:

import pulp

# Define the businesses and their profits and costs
companies = ["A", "B", "C"]
profits = [3, 2, 3]
costs = [2, 1, 1]

# Create a binary variable for each business indicating whether they should be bought
company_vars = pulp.LpVariable.dicts('company', companies, cat='Binary')

# Create the linear programming problem
lp_problem = pulp.LpProblem('Maximize Profit', pulp.LpMaximize)

# Add the objective function
lp_problem += pulp.lpSum([company_vars[i] * profits[i] for i in companies])

# Add the constraint that the total cost must be less than or equal to 3
lp_problem += pulp.lpSum([company_vars[i] * costs[i] for i in companies]) <= 3

# Solve the problem
lp_problem.solve()

# Print the optimal solution
print(f'Optimal profit: {lp_problem.objective.value()}')

# Print the businesses that should be bought in the solution
for i in companies:
  if company_vars[i].value() == 1:
    print(f'Business {i} should be bought.')

Below is the Error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-24525c5390b9> in <module>
     13 
     14 # Add the objective function
---> 15 lp_problem += pulp.lpSum([company_vars[i] * profits[i] for i in companies])
     16 
     17 # Add the constraint that the total cost must be less than or equal to 3

<ipython-input-21-24525c5390b9> in <listcomp>(.0)
     13 
     14 # Add the objective function
---> 15 lp_problem += pulp.lpSum([company_vars[i] * profits[i] for i in companies])
     16 
     17 # Add the constraint that the total cost must be less than or equal to 3

IndexError: list index out of range

TypeError: list indices must be integers or slices, not str

I was expecting the output:

Optimal profit: 6
Business A should be bought.
Business C should be bought.

Upvotes: 1

Views: 286

Answers (1)

J. M. Arnold
J. M. Arnold

Reputation: 6799

TypeError: list indices must be integers or slices, not str

You are trying to access the elements in companies with using string indices. You need to use ints to properly access list indices.

lp_problem += pulp.lpSum([company_vars[i] * profits[companies.index(i)] for i in companies])

lp_problem += pulp.lpSum([company_vars[i] * costs[companies.index(i)] for i in companies]) <= 3

Upvotes: 1

Related Questions