zrobione afla cięcie

This commit is contained in:
Neerka 2024-04-01 19:33:42 +02:00
parent e60c6ef28e
commit 162d362512
3 changed files with 104 additions and 0 deletions

15
item.py Normal file
View File

@ -0,0 +1,15 @@
import random
class Item:
def __init__(self):
self._waga = random.randint(1, 6)
self._wartosc = random.randint(5, 10)
@property
def waga(self):
return self._waga
@property
def wartosc(self):
return self._wartosc

38
main.py
View File

@ -0,0 +1,38 @@
from plecak import *
import copy
l = 4
dostepne = [Item() for _ in range(l)]
for x in dostepne:
print(x.waga, x.wartosc)
cap = 10
def knapsack(dostepne, cap):
def rekurencja(i, waga, val, alfa):
nonlocal max_val
if i >= len(dostepne) or waga==cap:
if val > max_val:
max_val = val
return
if val >= alfa:
return
if waga + dostepne[i].waga <= cap:
rekurencja(i+1, waga + dostepne[i].waga, val + dostepne[i].wartosc, alfa)
rekurencja(i+1, waga, val, alfa)
max_val = float("-inf")
rekurencja(0, 0, 0, 25)
return max_val
best = knapsack(dostepne, cap)
print("----------\n" + f'wartość plecaka: {best}\n')

51
plecak.py Normal file
View File

@ -0,0 +1,51 @@
from item import *
class Plecak:
def __init__(self):
self._capacity = 10
self._value = 0
self._items = []
self._waga = 0
@property
def capacity(self):
return self._capacity
@property
def value(self):
return self._value
@property
def items(self):
return self._items
@property
def waga(self):
return self._waga
@capacity.setter
def capacity(self, val):
self._capacity = val
@value.setter
def value(self, val):
self._value = val
@items.setter
def items(self, lista):
self._items = lista
@waga.setter
def waga(self, val):
self._waga = val
def addItem(self, item: Item):
if item not in self.items:
self._items.append(item)
self._value += item.wartosc
self._waga += item.waga
return self
def filled(self):
return True if self.waga == self.capacity else False