{"id":9602,"date":"2020-10-19T06:41:20","date_gmt":"2020-10-19T06:41:20","guid":{"rendered":"https:\/\/www.askpython.com\/?p=9602"},"modified":"2020-10-22T18:40:05","modified_gmt":"2020-10-22T18:40:05","slug":"knapsack-problem-dynamic-programming","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/knapsack-problem-dynamic-programming","title":{"rendered":"Solving 0\/1 Knapsack Using Dynamic programming in Python"},"content":{"rendered":"\n<p>In this article, we&#8217;ll solve the 0\/1 Knapsack problem using dynamic programming. <\/p>\n\n\n\n<p><em><strong>Dynamic Programming<\/strong> is an algorithmic technique for solving an optimization problem by breaking it down into simpler subproblems and utilizing the fact that the optimal solution to the overall problem depends upon the optimal solution to its subproblems<\/em><strong>.<\/strong><\/p>\n\n\n\n<p><strong>0\/1 Knapsack <\/strong>is perhaps the most popular problem under Dynamic Programming. It is also a great problem to learn in order to get a hang of Dynamic Programming. <\/p>\n\n\n\n<p>In this tutorial, we will be learning about what exactly is 0\/1 Knapsack and how can we solve it in Python using Dynamic Programming. <\/p>\n\n\n\n<p>Let&#8217;s get started. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Problem Statement for 0\/1 Knapsack<\/h2>\n\n\n\n<p>The problem statement of Dynamic programming is as follows :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nGiven weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack.\n<\/pre><\/div>\n\n\n<p>To begin with, we have a weight array that has the weight of all the items. We also have a value array that has the value of all the items and we have a total weight capacity of the knapsack. <\/p>\n\n\n\n<p>Given this information, we need to find the maximum value we can get while staying in the weight limit. <\/p>\n\n\n\n<p>The problem is called 0\/1 knapsack because we can <strong>either include an item as a whole or exclude it. That is to say,<\/strong> we can&#8217;t take a fraction of an item. <\/p>\n\n\n\n<p>Let&#8217;s take an example to understand. <\/p>\n\n\n\n<p>Take the following input values. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nval = &#x5B;50,100,150,200]\nwt = &#x5B;8,16,32,40]\nW = 64\n<\/pre><\/div>\n\n\n<p>Here we get the maximum profit when we include items<strong> 1,2 and 4<\/strong> giving us a total of<strong> 200 + 50 + 100 = 350. <\/strong><\/p>\n\n\n\n<p>Therefore the total profit comes out as :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n350 \n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">How to solve 0\/1 Knapsack using Dynamic Programming?<\/h2>\n\n\n\n<p>To solve 0\/1 knapsack using Dynamic Programming we construct a table with the following dimensions. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&#x5B;n + 1]&#x5B;W + 1]\n<\/pre><\/div>\n\n\n<p>The rows of the table correspond to items from <strong>0 to n<\/strong>.<\/p>\n\n\n\n<p>The columns of the table correspond to weight limit from <strong>0 to W.<\/strong><\/p>\n\n\n\n<p>The index of the very last cell of the table would be :<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n&#x5B;n]&#x5B;W]\n<\/pre><\/div>\n\n\n<p>Value of the cell with index [i][j] represents the maximum profit possible when considering items from 0 to i and the total weight limit as j. <\/p>\n\n\n\n<p>After filling the table our answer would be in the very last cell of the table. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How to fill the table?<\/h3>\n\n\n\n<p>Let&#8217;s start by setting the 0th row and column to 0. We do this because the 0th row means that we have no objects and the 0th column means that the maximum weight possible is 0.<\/p>\n\n\n\n<p>Now for each cell [i][j], we have two options : <\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Either we include object [i] in our final selection. <\/li><li>Or we don&#8217;t include object [i] in our final selection.<\/li><\/ol>\n\n\n\n<p><strong>How do we decide whether we include object [i] in our selection? <\/strong><\/p>\n\n\n\n<p>There are two conditions that should be satisfied to include object [i] : <\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The total weight after including object [i] should <strong>not exceed<\/strong> the <strong>weight limit. <\/strong><\/li><li>The <strong>profit <\/strong>after including object [i] should be<strong> greater<\/strong> as compared to when the object is not included. <\/li><\/ol>\n\n\n\n<p>Let&#8217;s convert our understanding of 0\/1 knapsack into python code. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Code to solve 0\/1 Knapsack <\/h2>\n\n\n\n<p>Let&#8217;s create a table using the following <a href=\"https:\/\/www.askpython.com\/python\/list\/python-list-comprehension\" class=\"rank-math-link\">list comprehension method<\/a>: <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ntable = &#x5B;&#x5B;0 for x in range(W + 1)] for x in range(n + 1)] \n<\/pre><\/div>\n\n\n<p>We will be using nested <a href=\"https:\/\/www.askpython.com\/python\/python-for-loop\" class=\"rank-math-link\">for loops<\/a> to traverse through the table and fill entires in each cell. <\/p>\n\n\n\n<p>We are going to fill the table in a bottom up manner. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfor i in range(n + 1): \n        for j in range(W + 1): \n            if i == 0 or j == 0: \n                table&#x5B;i]&#x5B;j] = 0\n            elif wt&#x5B;i-1] &lt;= j: \n                table&#x5B;i]&#x5B;j] = max(val&#x5B;i-1]  \n+ table&#x5B;i-1]&#x5B;j-wt&#x5B;i-1]],  table&#x5B;i-1]&#x5B;j]) \n            else: \n                table&#x5B;i]&#x5B;j] = table&#x5B;i-1]&#x5B;j] \n  \n<\/pre><\/div>\n\n\n<p><strong>Let&#8217;s breakdown the code line by line. <\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n  if i == 0 or j == 0: \n     table&#x5B;i]&#x5B;j] = 0\n<\/pre><\/div>\n\n\n<p>This part of the code is responsible for setting the 0th row and column to 0.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n elif wt&#x5B;i-1] &lt;= j: \n<\/pre><\/div>\n\n\n<p>This line of code checks that the weight of the i(th) object is less that the total weight permissible for that cell (j).<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n table&#x5B;i]&#x5B;j] = max(val&#x5B;i-1]  \n+ table&#x5B;i-1]&#x5B;j-wt&#x5B;i-1]],  table&#x5B;i-1]&#x5B;j]) \n<\/pre><\/div>\n\n\n<p>This line of code is responsible for selecting the maximum out of the two options available to us. We can either include the object or exclude it. <\/p>\n\n\n\n<p>Here the term <strong>table[i \u2013 1][j]<\/strong> means that ith item is not included. The term <strong>val[i \u2013 1] + table[i \u2013 1][j \u2013 wt[i \u2013 1]] <\/strong>represents that the ith item is included.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nelse:\n  table&#x5B;i]&#x5B;j] = table&#x5B;i-1]&#x5B;j]\n<\/pre><\/div>\n\n\n<p>This part of the loop is accessed when the weight of ith object is greater than the permissible limit (j).<\/p>\n\n\n\n<p>When we are done filling the table we can return the last cell of the table as the answer. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nreturn table&#x5B;n]&#x5B;W]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Complete code for the Knapsack solving function <\/h3>\n\n\n\n<p>The complete code for the function that solves the knapsack is given below : <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef knapSack(W, wt, val): \n    n=len(val)\n    table = &#x5B;&#x5B;0 for x in range(W + 1)] for x in range(n + 1)] \n\n    for i in range(n + 1): \n        for j in range(W + 1): \n            if i == 0 or j == 0: \n                table&#x5B;i]&#x5B;j] = 0\n            elif wt&#x5B;i-1] &lt;= j: \n                table&#x5B;i]&#x5B;j] = max(val&#x5B;i-1]  \n+ table&#x5B;i-1]&#x5B;j-wt&#x5B;i-1]],  table&#x5B;i-1]&#x5B;j]) \n            else: \n                table&#x5B;i]&#x5B;j] = table&#x5B;i-1]&#x5B;j] \n  \n    return table&#x5B;n]&#x5B;W] \n<\/pre><\/div>\n\n\n<p>Let&#8217;s try running the function for the example we took above. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nval = &#x5B;50,100,150,200]\nwt = &#x5B;8,16,32,40]\nW = 64\n\nprint(knapSack(W, wt, val))\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Complete Code <\/h2>\n\n\n\n<p>Here&#8217;s the complete code for you to run on your system. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef knapSack(W, wt, val): \n    n=len(val)\n    table = &#x5B;&#x5B;0 for x in range(W + 1)] for x in range(n + 1)] \n\n    for i in range(n + 1): \n        for j in range(W + 1): \n            if i == 0 or j == 0: \n                table&#x5B;i]&#x5B;j] = 0\n            elif wt&#x5B;i-1] &lt;= j: \n                table&#x5B;i]&#x5B;j] = max(val&#x5B;i-1]  \n+ table&#x5B;i-1]&#x5B;j-wt&#x5B;i-1]],  table&#x5B;i-1]&#x5B;j]) \n            else: \n                table&#x5B;i]&#x5B;j] = table&#x5B;i-1]&#x5B;j] \n  \n    return table&#x5B;n]&#x5B;W] \n\nval = &#x5B;50,100,150,200]\nwt = &#x5B;8,16,32,40]\nW = 64\n\nprint(knapSack(W, wt, val))\n<\/pre><\/div>\n\n\n<p><strong>Upon running the code, we get the following output :<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n350\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Conclusion <\/h2>\n\n\n\n<p>This tutorial was about solving 0\/1 Knapsack using Dynamic programming in Python. We hope you had fun learning with us! <\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we&#8217;ll solve the 0\/1 Knapsack problem using dynamic programming. Dynamic Programming is an algorithmic technique for solving an optimization problem by breaking it down into simpler subproblems and utilizing the fact that the optimal solution to the overall problem depends upon the optimal solution to its subproblems. 0\/1 Knapsack is perhaps the [&hellip;]<\/p>\n","protected":false},"author":14,"featured_media":9607,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-9602","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/9602","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=9602"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/9602\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/9607"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=9602"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=9602"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=9602"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}