avp26/u11/defknapsack.py

25 lines
712 B
Python

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):