Skip to content

Commit 503c3bd

Browse files
authored
Update fractional_cover_problem.py
1 parent 60d5b76 commit 503c3bd

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

Diff for: greedy_methods/fractional_cover_problem.py

+11
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ def fractional_cover(items: list[Item], capacity: int) -> float:
2222
float: The maximum value that can be obtained by selecting fractions of items to
2323
cover the knapsack's capacity.
2424
25+
Raises:
26+
ValueError: If the `capacity` is negative.
27+
2528
Examples:
2629
>>> items = [Item(10, 60), Item(20, 100), Item(30, 120)]
2730
>>> fractional_cover(items, 50)
@@ -54,7 +57,15 @@ def fractional_cover(items: list[Item], capacity: int) -> float:
5457
>>> items = [Item(1, 1)]
5558
>>> fractional_cover(items, 0)
5659
0.0
60+
61+
>>> items = [Item(10, 60)]
62+
>>> fractional_cover(items, -1)
63+
Traceback (most recent call last):
64+
...
65+
ValueError: Capacity cannot be negative
5766
"""
67+
if capacity < 0:
68+
raise ValueError("Capacity cannot be negative")
5869
# Calculate the value-to-weight ratios for each item
5970
ratios = [(item.value / item.weight, item) for item in items]
6071

0 commit comments

Comments
 (0)