Update u11/defknapsack.py
This commit is contained in:
parent
d5cdbf06ff
commit
fd8b29ef5e
24
u11/defknapsack.py
Normal file
24
u11/defknapsack.py
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
def build_table(maximum_weight, items):
|
||||||
|
count = len (items)
|
||||||
|
table = [[0] * (maximum_weight + 1) fot i in range(count + 1)]
|
||||||
|
|
||||||
|
for i in range(1, count + 1):
|
||||||
|
weight = items[i - 1]["weight"]
|
||||||
|
value = items[i - 1]["value"]
|
||||||
|
|
||||||
|
for w in range(maximum_weight + 1):
|
||||||
|
table[i][w] = table[i - 1][w]
|
||||||
|
|
||||||
|
if weight <=w:
|
||||||
|
with_item = table[i - 1][w - weight] + value
|
||||||
|
if with_item > table[1][w]:
|
||||||
|
table[i][w] = with_item
|
||||||
|
return table
|
||||||
|
|
||||||
|
def maximum_value(maximum_weight, items):
|
||||||
|
table = build_table(maximum_weight, items)
|
||||||
|
return table[len(items)][maximum_weight]
|
||||||
|
|
||||||
|
|
||||||
|
def maximum_value_with_items(maximum_weight, items):
|
||||||
|
|
||||||
Loading…
Reference in New Issue
Block a user