Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
using OrderedDict solution in Clear category for Treasures by Merzix
from collections import OrderedDict
def treasures(info, limit):
limit = int(limit * 1000) # kg -> g
items = OrderedDict(sorted(info.items(), key=lambda i: -i[1]['price'] / i[1]['weight']))
for v in items.values():
v['taken'] = min([limit // v['weight'], v['amount']])
limit -= v['taken'] * v['weight']
if not limit: break
return sorted([f'{k}: {v["taken"]}' for k,v in items.items() if v.get("taken", 0)],
key=lambda x: x[3])
if __name__ == '__main__':
assert treasures({'golden coin':
{'price': 100, 'weight': 50, 'amount': 200},
'silver coin':
{'price': 10, 'weight': 20, 'amount': 1000},
'ruby':
{'price': 1000, 'weight': 200, 'amount': 2}}, 5) == [
'golden coin: 92', 'ruby: 2']
assert treasures({'golden coin':
{'price': 100, 'weight': 50, 'amount': 100},
'silver coin':
{'price': 10, 'weight': 20, 'amount': 100},
'ruby':
{'price': 1000, 'weight': 200, 'amount': 1}}, 7.5) == [
'golden coin: 100', 'silver coin: 100', 'ruby: 1']
Sept. 17, 2018
Comments: