Untitled

mail@pastecode.io avatar
unknown
python
a year ago
1.6 kB
3
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, content=None):
        if content is None:
            content = []
        self.capacity = capacity
        self.content = 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 - len(self.content)

    def value(self):
        return sum(g.price for g in self.content)

    def pack(self, gift_list):
        gift_list.sort(key=lambda g: g.price / g.weight)
        for g in gift_list:
            print(g)
            self.content.append(g)


bag = Bag(20)
bag.pack(gifts)
Leave a Comment