88
99from __future__ import annotations
1010
11+ from collections .abc import Sequence
1112from functools import lru_cache
1213
1314
14- def mf_knapsack (i : int , wt : list [int ], val : list [int ], j : int ) -> int :
15+ def mf_knapsack (i : int , wt : Sequence [int ], val : Sequence [int ], j : int ) -> int :
1516 """
1617 Return the optimal value for the 0/1 knapsack problem using memoization.
1718
@@ -53,7 +54,7 @@ def solve(item_count: int, capacity: int) -> int:
5354
5455
5556def knapsack (
56- w : int , wt : list [int ], val : list [int ], n : int
57+ w : int , wt : Sequence [int ], val : Sequence [int ], n : int
5758) -> tuple [int , list [list [int ]]]:
5859 dp = [[0 ] * (w + 1 ) for _ in range (n + 1 )]
5960
@@ -67,7 +68,9 @@ def knapsack(
6768 return dp [n ][w ], dp
6869
6970
70- def knapsack_with_example_solution (w : int , wt : list , val : list ) -> tuple [int , set [int ]]:
71+ def knapsack_with_example_solution (
72+ w : int , wt : Sequence [int ], val : Sequence [int ]
73+ ) -> tuple [int , set [int ]]:
7174 """
7275 Solves the integer weights knapsack problem returns one of
7376 the several possible optimal subsets.
@@ -101,9 +104,14 @@ def knapsack_with_example_solution(w: int, wt: list, val: list) -> tuple[int, se
101104 ValueError: The number of weights must be the same as the number of values.
102105 But got 4 weights and 3 values
103106 """
104- if not (isinstance (wt , (list , tuple )) and isinstance (val , (list , tuple ))):
107+ if not (
108+ isinstance (wt , Sequence )
109+ and not isinstance (wt , (str , bytes ))
110+ and isinstance (val , Sequence )
111+ and not isinstance (val , (str , bytes ))
112+ ):
105113 raise ValueError (
106- "Both the weights and values vectors must be either lists or tuples "
114+ "Both the weights and values vectors must be non-string sequences "
107115 )
108116
109117 num_items = len (wt )
@@ -129,7 +137,7 @@ def knapsack_with_example_solution(w: int, wt: list, val: list) -> tuple[int, se
129137
130138
131139def _construct_solution (
132- dp : list [list [int ]], wt : list [int ], i : int , j : int , optimal_set : set [int ]
140+ dp : list [list [int ]], wt : Sequence [int ], i : int , j : int , optimal_set : set [int ]
133141) -> None :
134142 """
135143 Recursively reconstructs one of the optimal subsets given
0 commit comments