Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
OOP solution in Clear category for Treasures by ssk8
class Treasure:
def __init__(self, name, info):
self.name = name
self.price = info['price']
self.weight = info['weight']
self.amount = info['amount']
self.in_bag = 0
class Bag:
def __init__(self, treasure, limit):
self.contents = [Treasure(k, v) for k, v in treasure.items()]
self.limit = limit*1000
@property
def contents_weight(self):
return sum([i.weight * i.in_bag for i in self.contents])
def contents_list(self):
l = [x for x in self.contents]
l = sorted(l, key=lambda x: ('golden coin', 'silver coin', 'ruby').index(x.name))
return [f'{i.name}: {int(i.in_bag)}' for i in l if i.in_bag]
def fill(self):
for treasure in sorted(self.contents, key=lambda x: x.price / x.weight, reverse=True):
treasure.in_bag = min((self.limit - self.contents_weight) // treasure.weight, treasure.amount)
def treasures(info, limit):
bag = Bag(info, limit)
bag.fill()
return bag.contents_list()
Sept. 17, 2018
Comments: