Fractional Knapsack Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Fractional Knapsack runs in O(n log n) time and O(1) space, in Python as in every other language.
- ✓dataclasses gives Item a cheap, comparison-free record type; the ratio itself belongs on the class as a @property so it is computed from a single source of truth rather than duplicated at every call site.
- ✓Sort with sorted(items, key=attrgetter('ratio'), reverse=True) rather than sorting ascending and slicing [::-1] - reverse=True is handled inside the sort itself and keeps items with equal ratios in their original relative order, while a post-hoc reversal of an ascending sort flips that order.
- ✓The Python trap: value / weight raises ZeroDivisionError the moment an item has weight == 0.0. That is different from every other language below - all of them follow IEEE-754 and produce inf for a positive value divided by 0.0, so code ported from any of those into Python crashes instead of quietly mis-sorting a zero-weight item to the front.
- ✓sorted()'s key function is called exactly once per element before any comparisons happen - the decorate-sort-undecorate pattern is built into the C implementation, so the ratio is not recomputed at every comparison the way a raw cmp callback would recompute it.
What Fractional Knapsack actually is
Fractional Knapsack in Python: what you actually reach for
Python implementation
from dataclasses import dataclass
from operator import attrgetter
@dataclass(frozen=True)
class Item:
name: str
weight: float
value: float
@property
def ratio(self) -> float:
return self.value / self.weight # raises ZeroDivisionError at weight == 0.0
def fractional_knapsack(items: list[Item], capacity: float) -> float:
# key is called once per element (decorate-sort-undecorate), not per comparison;
# reverse=True keeps tied ratios in their original relative order - a plain
# [::-1] on an ascending sort would flip that order instead
by_ratio = sorted(items, key=attrgetter("ratio"), reverse=True)
total_value = 0.0
remaining = capacity
for item in by_ratio:
if remaining <= 0:
break
if item.weight <= remaining:
total_value += item.value
remaining -= item.weight
else:
total_value += item.ratio * remaining
remaining = 0.0
return total_valueThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Fractional Knapsack?
dataclasses gives Item a cheap, comparison-free record type; the ratio itself belongs on the class as a @property so it is computed from a single source of truth rather than duplicated at every call site. operator.attrgetter builds the sort key without a lambda's extra interpreter frame per element, and comparing remaining capacity to zero needs an explicit absolute tolerance -- math.isclose(remaining, 0.0, abs_tol=1e-9), never the bare math.isclose(remaining, 0) or remaining == 0, since isclose's default abs_tol=0.0 makes its relative-tolerance check degenerate against a zero reference and it will not catch the small nonzero residue that accumulated floating-point error leaves behind.
What is the most common Python mistake when implementing Fractional Knapsack?
value / weight raises ZeroDivisionError the moment an item has weight == 0.0. That is different from every other language below - all of them follow IEEE-754 and produce inf for a positive value divided by 0.0, so code ported from any of those into Python crashes instead of quietly mis-sorting a zero-weight item to the front. A zero-weight item needs a special case, not a bare division.
How does Fractional Knapsack actually perform in Python?
sorted()'s key function is called exactly once per element before any comparisons happen - the decorate-sort-undecorate pattern is built into the C implementation, so the ratio is not recomputed at every comparison the way a raw cmp callback would recompute it. The greedy fill loop itself is O(1) space: one running total, one remaining-capacity counter. Timsort is not - its worst-case merge step needs up to O(n) auxiliary space, so the O(1) space bound describes the fill loop, not the whole function. Time complexity is O(n log n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.