How to Implement Fractional Knapsack in Python
In this tutorial, we will learn "How to Implement Fractional Knapsack in Python". The main objective is to understand the fractional knapsack problem and its implementation. This guide will walk you step by step through the process, making it easier to follow and apply. By the end of this tutorial, you will have a solid understanding of how fractional knapsack works in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.
This topic is straightforward and easy to understand. By following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of implementing Fractional Knapsack. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of Python.
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- def fractional_knapsack(value, weight, capacity):
- index = list(range(len(value)))
- ratio = [v / w for v, w in zip(value, weight)]
- index.sort(key=lambda i: ratio[i], reverse=True)
- max_value = 0
- fractions = [0] * len(value)
- for i in index:
- if weight[i] <= capacity:
- fractions[i] = 1
- max_value += value[i]
- capacity -= weight[i]
- else:
- fractions[i] = capacity / weight[i]
- max_value += value[i] * fractions[i]
- break
- return max_value, fractions
- # MAIN LOOP
- while True:
- print("\n============= Implement Fractional Knapsack =============\n")
- # Input number of items
- try:
- n = int(input('Enter number of items: '))
- if n <= 0:
- print("Number of items must be positive.")
- continue
- except ValueError:
- print("Invalid input.")
- continue
- # Input values
- try:
- value = list(map(int, input(f'Enter {n} values: ').split()))
- if len(value) != n:
- print("You must enter exactly", n, "values.")
- continue
- except ValueError:
- print("Invalid values.")
- continue
- # Input weights
- try:
- weight = list(map(int, input(f'Enter {n} weights: ').split()))
- if len(weight) != n:
- print("You must enter exactly", n, "weights.")
- continue
- if any(w <= 0 for w in weight):
- print("Weights must be positive.")
- continue
- except ValueError:
- print("Invalid weights.")
- continue
- # Input capacity
- try:
- capacity = int(input('Enter maximum weight: '))
- if capacity < 0:
- print("Capacity cannot be negative.")
- continue
- except ValueError:
- print("Invalid capacity.")
- continue
- # Run algorithm
- max_value, fractions = fractional_knapsack(value, weight, capacity)
- print(f"\nMaximum value: {max_value}")
- print(f"Fractions taken: {fractions}")
- # Try Again Option
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == "no":
- print("Exiting program...")
- break
- elif opt != "yes":
- print("Invalid choice. Exiting program...")
- break
This Python program implements the Fractional Knapsack algorithm using a greedy approach to maximize the total value within a given weight capacity. It calculates the value-to-weight ratio of each item, sorts them in descending order, and selects items fully or partially based on the remaining capacity. The program runs interactively, allowing users to input item values, weights, and capacity, then outputs the maximum achievable value along with the fraction of each item taken. It also includes input validation and lets users repeat the process or exit.
Output:
There you have it we successfully created How to Implement Fractional Knapsack in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language