Fractional Knapsack
Detailed guide and Python implementation for the 'Fractional Knapsack' problem.
Problem Statement
Write a function fractional_knapsack(W, items) that takes the knapsack capacity W and a list of tuples items where each tuple is (value, weight). Find the maximum total value obtainable in the knapsack, allowing items to be broken/fractioned. Round the output to 2 decimal places.
- •1 <= len(items) <= 1000
- •1 <= W <= 10^5
- •1 <= value, weight <= 10^4
Examples
fractional_knapsack(50, [(60, 10), (100, 20), (120, 30)])
240.0
Take the first and second item fully, and 2/3 of the third item. Total value: 60 + 100 + 120 * (20/30) = 240.0.
fractional_knapsack(15, [(24, 10), (18, 10), (15, 10)])
33.0
Take the first item fully, and 1/2 of the second item. Total value: 24 + 18 * 0.5 = 33.0.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.