Untitled
unknown
python
2 years ago
1.8 kB
8
Indexable
import random
##
# 1A
class Gift:
def __init__(self, weight, price):
self.weight = weight
self.price = price
def __str__(self):
return f"Prezent, waga: {self.weight}, cena: {self.price}"
def __repr__(self):
return str(self)
@staticmethod
def random_gift(min_weight=1, max_weight=20, min_price=1, max_price=1000):
return Gift(
weight=random.randrange(min_weight, max_weight),
price=random.randrange(min_price, max_price)
)
def __gt__(self, other):
return self.price > other.price
def custom_key(self):
if self.weight >= 10:
return 1, self.price
return 2, -self.price
##
# 1B
gifts = [Gift.random_gift() for _ in range(20)]
gifts.sort()
print(gifts)
gifts.sort(key=Gift.custom_key)
print(gifts)
##
# 1C
class Bag:
def __init__(self, capacity):
self.capacity = capacity
self.content = []
def __str__(self):
return f"Plecak, pojemnosc: {self.capacity}, zawartosc: {self.content}"
def __repr__(self):
return str(self)
def add(self, gift):
self.content.append(gift)
def left_capacity(self):
return self.capacity - sum(g.weight for g in self.content)
def value(self):
return sum(g.price for g in self.content)
def pack(self, gift_list):
while True:
gift_list = list(filter(lambda g: g.weight < self.left_capacity(), gift_list))
gift_list.sort(key=lambda g: g.price / g.weight)
for g in gift_list:
if self.left_capacity() >= g.weight:
self.add(g)
gift_list.remove(g)
if len(gift_list) == 0:
break
bag = Bag(20)
bag.pack(gifts)
Editor is loading...
Leave a Comment