Skip to content

Commit ecd8634

Browse files
committed
Add input validation for capacity and max_items
1 parent 168e1cd commit ecd8634

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

greedy_methods/fractional_knapsack.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,21 @@ def frac_knapsack(
3434
...
3535
ValueError: zip() argument 2 is longer than argument 1
3636
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 0, 4)
37-
0
37+
Traceback (most recent call last):
38+
...
39+
ValueError: Capacity and max_items must be greater than 0
3840
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 0)
39-
95.0
41+
Traceback (most recent call last):
42+
...
43+
ValueError: Capacity and max_items must be greater than 0
4044
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], -8, 4)
41-
0
45+
Traceback (most recent call last):
46+
...
47+
ValueError: Capacity and max_items must be greater than 0
4248
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, -4)
43-
95.0
49+
Traceback (most recent call last):
50+
...
51+
ValueError: Capacity and max_items must be greater than 0
4452
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 800, 4)
4553
130
4654
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 400)
@@ -51,6 +59,10 @@ def frac_knapsack(
5159
TypeError: unsupported operand type(s) for /: 'str' and 'int'
5260
"""
5361

62+
# Input validation
63+
if capacity <= 0 or max_items <= 0:
64+
raise ValueError("Capacity and max_items must be greater than 0")
65+
5466
# sort in descending order of value/weight ratio
5567
r = sorted(
5668
zip(values, weights, strict=True), key=lambda x: x[0] / x[1], reverse=True

0 commit comments

Comments
 (0)