Share Lots Sold Oldest First
Implement a class Portfolio that tracks shares of one stock bought in lots and always sells from the oldest lot first. Write these methods:
Portfolio()starts with no shares.buy(qty, price)buysqtyshares atpriceeach as a new lot. Returns how many shares are held now.sell(qty, price)sellsqtyshares atpriceeach. The shares come from the oldest lot first, then from the next oldest, and so on; a lot may be sold in part. Returns the profit of this sale:qty * priceminus what those shares cost when they were bought. It is never called with more shares than are held.get_cost_basis()returns what the shares held now cost in total.oldest_lot()returns[qty, price]for what is left of the oldest lot, or[]if no shares are held.get_total_profit()returns the sum of the profits of all sales so far.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
Portfolio()
buy(10, 5) returns 10
buy(10, 8) returns 20
sell(12, 9) returns 42
oldest_lot() returns [8,8]
get_cost_basis() returns 64
sell(3, 4) returns -12
get_total_profit() returns 30
The sale of 12 shares uses all 10 bought at 5 and 2 of those bought at 8, so they cost 66 and bring in 108. The second sale loses money: 12 comes in for shares that cost 24.
Constraints
1 <= qty <= 201 <= price <= 50sellnever asks for more shares than are held- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.