@@ -34,13 +34,21 @@ def frac_knapsack(
34
34
...
35
35
ValueError: zip() argument 2 is longer than argument 1
36
36
>>> 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
38
40
>>> 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
40
44
>>> 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
42
48
>>> 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
44
52
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 800, 4)
45
53
130
46
54
>>> frac_knapsack([10, 40, 30, 50], [5, 4, 6, 3], 8, 400)
@@ -51,6 +59,10 @@ def frac_knapsack(
51
59
TypeError: unsupported operand type(s) for /: 'str' and 'int'
52
60
"""
53
61
62
+ # Input validation
63
+ if capacity <= 0 or max_items <= 0 :
64
+ raise ValueError ("Capacity and max_items must be greater than 0" )
65
+
54
66
# sort in descending order of value/weight ratio
55
67
r = sorted (
56
68
zip (values , weights , strict = True ), key = lambda x : x [0 ] / x [1 ], reverse = True
0 commit comments