45 lines
968 B
Python
45 lines
968 B
Python
from plecak import *
|
|
|
|
l = 10
|
|
dostepne = [Item() for _ in range(l)]
|
|
|
|
for x in dostepne:
|
|
print(x.waga, x.wartosc)
|
|
|
|
cap = 25
|
|
|
|
|
|
def knapsack(dostepne, cap):
|
|
def rekurencja(i, waga, val, items, alfa):
|
|
nonlocal max_val, plecak
|
|
|
|
if i >= len(dostepne) or waga == cap:
|
|
if val > max_val:
|
|
max_val = val
|
|
plecak = items
|
|
return
|
|
|
|
if val >= alfa:
|
|
plecak = items
|
|
return
|
|
|
|
rekurencja(i+1, waga, val, items, alfa)
|
|
|
|
if waga + dostepne[i].waga <= cap:
|
|
temp = items[:]
|
|
temp.append(dostepne[i])
|
|
rekurencja(i+1, waga + dostepne[i].waga, val + dostepne[i].wartosc, temp, alfa)
|
|
|
|
max_val = float("-inf")
|
|
plecak = []
|
|
rekurencja(0, 0, 0, [], 60)
|
|
return max_val, plecak
|
|
|
|
|
|
best, final = knapsack(dostepne, cap)
|
|
|
|
|
|
print("----------\n" + f'wartość plecaka: {best}')
|
|
for item in final:
|
|
print(item.waga, item.wartosc)
|