<jupyter_start><jupyter_text>Knapsack ProblemBin packing tried to minimize the number of bins needed for a fixed number of items, if we instead fix the number of bins and assign some way to value objects, then the knapsack problem tells us which objects to take to maximize our total item value. Rather than object sizes, in the traditional formulation we consider item weights and imagine that we are packing a backpack for a camping trip or a suitcase for a vacation. How many items of different weights can we fit in our suitcase before our suitcase is too heavy. Which objects should we take?This problems is also known as the capital budgeting problem. Instead of items we think of investment opportunities, instead of value we consider investment return, weight becomes value, and the maximum weight we can carry becomes our budget. Which investments should we take on to maximize our return with the current budget?<jupyter_code>from pulp import *
import numpy as np<jupyter_output><empty_output><jupyter_text>1. First lets make some fake data<jupyter_code>items=['item_%d'%i for i in range(20)]
item_weights = dict( (i,np.random.randint(1,20)) for i in items)
item_values = dict( (i,10*np.random.rand()) for i in items)
W = 100
#variables. How many of each object to take. For simplicity lets make this 0 or 1 (classic 0-1 knapsack problem)
x = LpVariable.dicts('item',items,0,1, LpBinary)
#create the problme
prob=LpProblem("knapsack",LpMaximize)
#the objective
cost = lpSum([ item_values[i]*x[i] for i in items])
prob+=cost
#constraint
prob += lpSum([ item_weights[i]*x[i] for i in items]) <= W<jupyter_output><empty_output><jupyter_text>Solve it!<jupyter_code>%time prob.solve()
print(LpStatus[prob.status])<jupyter_output>CPU times: user 2.45 ms, sys: 4.37 ms, total: 6.82 ms
Wall time: 20.5 ms
Optimal<jupyter_text>And the result:<jupyter_code>for i in items:
    print(i, value(x[i]))
print(value(prob.objective))
print(sum([ item_weights[i]*value(x[i]) for i in items]))<jupyter_output>100.0
{'fraction_non_alphanumeric': 0.0872382851445663, 'fraction_numerical': 0.016450648055832504, 'mean_word_length': 5.780405405405405, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '325054', 'license': 'MIT', 'n_tokens_mistral': 642, 'n_tokens_neox': 608, 'n_words': 262, 'path': '04-packing-and-allocation/knapsack_problem.ipynb', 'repo_name': 'cochoa0x1/intro-mathematical-programming', 'size': '2006'}