{ "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", "# [START program]\n", "\"\"\"A simple knapsack problem.\"\"\"\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_DYNAMIC_PROGRAMMING_SOLVER, \"test\")\n", "# [END solver]\n", "\n", "# [START data]\n", "weights = [[\n", " 565, 406, 194, 130, 435, 367, 230, 315, 393, 125, 670, 892, 600, 293,\n", " 712, 147, 421, 255\n", "]]\n", "capacities = [850]\n", "values = weights[0]\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", " x for x in range(0, len(weights[0])) if solver.BestSolutionContains(x)\n", "]\n", "packed_weights = [weights[0][i] for i in packed_items]\n", "\n", "print(\"Packed items: \", packed_items)\n", "print(\"Packed weights: \", packed_weights)\n", "print(\"Total weight (same as total value): \", computed_value)\n", "# [END print_solution]\n", "\n" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 4 }