×

Python Knapsack problem

Python Knapsack problem

Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem.

What is a knapsack problem?

A problem from the optimization combinational related issues is known as a knapsack problem. This problem often arises in our daily life in resources allocations where the decisions have to be made from the set of items that are non-divisible tasks or projects which are placed under a fixed budget constraints or time constraint.

Example of knapsack problem

Suppose we have given a set of items; each have a given value (in terms of money on anything) and a given weight such as the total combine weight of items is more than the actual limit. So, here we have to maximize the value within the limit. It means we have to choose the items that have more value and less weight and that's how we can get maximum value within the limit.

This is the classical example of a one-dimensional Knapsack problem.

Note:The word Knapsack itself means a 'bag'.

Knapsack Problem in Python

As of now, we have a basic understanding about the knapsack problems and how a one-dimensional Knapsack problem looks like. Here, in this tutorial, we will discuss about that how we can solve the knapsack problem using Python. We will take 2 example knapsack problems and design a Python program for each to solve them with the dynamic programming. And, after that we will see the explanation of the program to understand the logic and working of it.

  • Important:The knapsack problem (particularly of one-dimension) is referred to as 0/1 knapsack problem in Python and it is the most popular type problem in a dynamically typed programming language.

Now, let's discuss about a 0/1 knapsack problem and approaches we are using to design its solution program in Python. Basically, we use any of the following two approaches to design a solution Python program for any 0/1 knapsack problem:

1. Designing solution program using Brute-force approach

2. Designing solution program using dynamic approach

Let's see their implementation of these approaches.

Given 0/1 knapsack problem

We have a given number of items and these items have their respective weight and value. We have to place these items inside a bag that have a weighing capacity (Let's say W). We have to get the maximum value in the bag from the given items and we have to answer the maximum number of values that we can get in the bag within the limit of it.

Solution 1: Using Brute-force approach in solution program:

 # Define a default knapsack 01 function
 def knapsack01 (MLimit, WeightofItem, ValueofItem, NumberOI):
    # Give the initial if conditions
    if NumberOI == 0 or MLimit == 0 :
       return 0
    # Defining nested if condition for higher weight
    if (WeightofItem [NumberOI-1] > MLimit):
       return knapsack01 (MLimit, WeightofItem, ValueofItem, NumberOI-1)
    # Using else condition for number of items
    else:
       return max (ValueofItem [NumberOI-1] + knapsack01 (MLimit-WeightofItem [NumberOI-1], WeightofItem, ValueofItem, NumberOI-1),
          knapsack01 (MLimit, WeightofItem, ValueofItem, NumberOI-1))
 # Defining variables used in the function
 ValueofItem = [5, 10, 20, 50, 100, 200, 500, 2000]
 WeightofItem = [1, 4, 8, 16, 24, 32, 36, 40]
 NumberOI = len (ValueofItem)
 # Taking maximum limit as user input
 MLimit = int (input ("Enter the maximum limit for the bag: "))
 # Printing result of problem in the output
 print ("The maximum value of items we can get with the given limit: ")
 print (knapsack01 (MLimit, WeightofItem, ValueofItem, NumberOI)) 

Output:

 Enter the maximum limit for the bag: 97
 The maximum value of items we can get with the given limit:
 2565 

Explanation:

 In this program, we have implemented the brute-force approach for the solution of given problem. We have defined a knapsack function and give variables of the problems i.e., Maximum limit of bag, Weight of each item, Value of each item and Number of items, as the arguments in this function.

Then, we used nested if else condition in the function with the given variables to apply the brute-force approach in the program.

We get maximum value and all the findings in this nested if else condition. After that, we have defined the values of the given variables in function i.e., Values of items, Weight of items and number of items respectively in list format.

After that, we defined the maximum limit of the bag variable to user input. After that, we called out the function to print the result as maximum value can be stored in bag. When the program will get the maximum limit of bag as user input, the result for maximum value in the bag with respect to maximum limit, will be printed in the output.

Solution 2: Using dynamic approach in solution program:

 # Define a default knapsack 01 function
 def knapsack01 (MLimit, WeightofItem, ValueofItem, NumberOI):
    M = [ [0 for a in range (MLimit + 1)] for a in range (NumberOI + 1)]
    # Define a for loop for limit
    for b in range (NumberOI + 1):
       # Nested for loop for higher limit
       for c in range (MLimit + 1):
          # Defining if condition for maximum weight
          if b == 0 or c == 0:
             M[b][c] = 0
          # Elseif condition for maximum value in bag
          elif WeightofItem[b-1] <= c:
             M[b][c] = max (ValueofItem[b-1] + M[b-1][c-WeightofItem[b-1]], M[b-1][c])
          else:
             M[b][c] = M[b-1][c]
    return M[NumberOI][MLimit] # returning maximum value from the function
 # Defining variables used in the function
 ValueofItem = [5, 10, 20, 50, 100, 200, 500, 2000]
 WeightofItem = [1, 4, 8, 16, 24, 32, 36, 40]
 NumberOI = len (ValueofItem)
 # Taking maximum limit as user input
 MLimit = int (input ("Enter the maximum limit for the bag: "))
 # Printing result of problem in the output
 print ("The maximum value of items we can get with the given limit: ")
 print (knapsack01 (MLimit, WeightofItem, ValueofItem, NumberOI)) 

Output:

 Enter the maximum limit for the bag: 69
 The maximum value of items we can get with the given limit:
 2115 

Explanation –

In this program, after defining the knapsack function we used the dynamic approach in the function.

We used nested for loop with the arguments of the function. In the nested for loop, we have defined a nested if else condition.

We used variables in the elseif and if condition to get the maximum value result. Then, we have defined variable values in list format and get the user input of maximum limit. We get the result of maximum value of bag using dynamic approach after giving maximum limit of bag as user input.

Conclusion:

In this tutorial, we learned about knapsack problem. We learned about knapsack 0/1 problem in Python. We also learned about the both approaches i.e., brute-force approach & dynamic approach, that we use in our Python program to solve the knapsack 0/1 problem.


Related Topics

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Raise Exception in Python

Most of the programmers/developers create large programs to solve complex tasks in Python. The code can be of 1000 lines and even more based on the need of the problem....

5 minutes read.

Io stringio Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

7 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

Python JSON Schema

Python-jsonschema JSON: JSON stands for JavaScript Object Notation. It is a text-based format that represents structured data and can be used to interchange data among various applications. This is self-defining language...

5 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Python Recursion

Recursion is one of the most interesting yet important concepts of any programming language. If you want to be a good programmer or data scientist, then you should better have...

4 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

Iterate a Dictionary in Python – Part 2

In this tutorial, we will learn above various methods used to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to...

3 minutes read.