Editor

First In, First Out Stock

#357 · Working with data · Advanced · 125 XP · about 25 min

A shop buys stock in batches at different prices and sells it over time. Under first-in, first-out (FIFO) accounting, every sale uses up the oldest units still in stock first, and the cost of goods sold is what those units cost when they were bought.

trades is a list in time order of ('buy', quantity, unit_cost) and ('sell', quantity, unit_price) tuples, all whole numbers (prices in cents). Write fifo(trades) that returns a tuple (cost_of_goods_sold, profit, units_left, value_left): the total cost of all the units sold, the total money from sales minus that cost, the number of units still in stock, and what those units cost to buy.

If a sale asks for more units than are in stock, raise ValueError.

Examples

fifo([('buy', 10, 100), ('buy', 5, 120), ('sell', 12, 150), ('buy', 8, 90), ('sell', 4, 160)])
# returns (1690, 750, 7, 630)

The first sale takes all 10 units bought at 100 and 2 of those at 120, costing 1,240. The second takes the 3 units left at 120 and 1 at 90, costing 450. Sales bring in 1,800 + 640 = 2,440, and the 7 units still in stock all cost 90.

Constraints

  • 0 <= len(trades) <= 100000
  • Quantities from 1 to 1,000,000, so a single batch can hold a million units.
  • Prices from 1 to 100,000.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.