Skip to content

Commit 07539cb

Browse files
committed
Harden knapsack_space_optimized input validation
1 parent c93841e commit 07539cb

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

dynamic_programming/knapsack.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,42 @@ def knapsack_space_optimized(
5454
0
5555
>>> knapsack_space_optimized(6, [4, 3, 2, 3], [3, 2, 4, 4], 4)
5656
8
57+
>>> knapsack_space_optimized(-1, [1], [1], 1)
58+
Traceback (most recent call last):
59+
...
60+
ValueError: The knapsack capacity cannot be negative.
61+
>>> knapsack_space_optimized(1, [1], [1], -1)
62+
Traceback (most recent call last):
63+
...
64+
ValueError: The number of items cannot be negative.
65+
>>> knapsack_space_optimized(1, [1], [1], 2)
66+
Traceback (most recent call last):
67+
...
68+
ValueError: The number of items exceeds the provided input lengths.
69+
>>> knapsack_space_optimized(1, [-1], [1], 1)
70+
Traceback (most recent call last):
71+
...
72+
ValueError: Weight at index 0 cannot be negative.
73+
>>> knapsack_space_optimized(1, [1], [1.5], 1)
74+
Traceback (most recent call last):
75+
...
76+
TypeError: Value at index 0 must be an integer.
5777
"""
5878
if num_items < 0:
5979
raise ValueError("The number of items cannot be negative.")
6080
if capacity < 0:
6181
raise ValueError("The knapsack capacity cannot be negative.")
6282
if num_items > len(weights) or num_items > len(values):
6383
raise ValueError("The number of items exceeds the provided input lengths.")
84+
for item_index in range(num_items):
85+
item_weight = weights[item_index]
86+
item_value = values[item_index]
87+
if not isinstance(item_weight, int):
88+
raise TypeError(f"Weight at index {item_index} must be an integer.")
89+
if item_weight < 0:
90+
raise ValueError(f"Weight at index {item_index} cannot be negative.")
91+
if not isinstance(item_value, int):
92+
raise TypeError(f"Value at index {item_index} must be an integer.")
6493

6594
dp = [0] * (capacity + 1)
6695
for item_index in range(num_items):

0 commit comments

Comments
 (0)