Files
ortools-clone/examples/notebook/algorithms/knapsack.ipynb
Corentin Le Molgat 27121a1068 Update examples/notebook
generated using ./tools/gen_all_notebook.sh
2020-03-04 14:34:33 +01:00

78 lines
2.7 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Copyright 2010-2018 Google LLC\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# http://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License.\n",
"\"\"\"A simple knapsack problem.\"\"\"\n",
"# [START program]\n",
"# [START import]\n",
"from __future__ import print_function\n",
"from ortools.algorithms import pywrapknapsack_solver\n",
"# [END import]\n",
"\n",
"\n",
"# Create the solver.\n",
"# [START solver]\n",
"solver = pywrapknapsack_solver.KnapsackSolver(\n",
" pywrapknapsack_solver.KnapsackSolver.\n",
" KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')\n",
"# [END solver]\n",
"\n",
"# [START data]\n",
"values = [\n",
" 360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,\n",
" 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28,\n",
" 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276,\n",
" 312\n",
"]\n",
"weights = [[\n",
" 7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,\n",
" 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,\n",
" 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13\n",
"]]\n",
"capacities = [850]\n",
"# [END data]\n",
"\n",
"# [START solve]\n",
"solver.Init(values, weights, capacities)\n",
"computed_value = solver.Solve()\n",
"# [END solve]\n",
"\n",
"# [START print_solution]\n",
"packed_items = []\n",
"packed_weights = []\n",
"total_weight = 0\n",
"print('Total value =', computed_value)\n",
"for i in range(len(values)):\n",
" if solver.BestSolutionContains(i):\n",
" packed_items.append(i)\n",
" packed_weights.append(weights[0][i])\n",
" total_weight += weights[0][i]\n",
"print('Total weight:', total_weight)\n",
"print('Packed items:', packed_items)\n",
"print('Packed_weights:', packed_weights)\n",
"# [END print_solution]\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}