You are a newsvendor. Each morning, before demand is known, you order q newspapers at unit cost cost. Demand is discrete: value demand[i] occurs with probability probs[i]. You sell each copy at price. Leftovers are worth salvage. Unmet demand earns nothing.
When demand realizes as d, profit is
Return the expected profit of ordering q newspapers:
Input: q = 3
demand = [0, 1, 2, 3, 4, 5]
probs = [0.05, 0.15, 0.25, 0.25, 0.20, 0.10]
cost = 2, price = 5, salvage = 0
Output: 5.5
Walk each possible d. For d = 0 you lose 6 (contribution −0.30). For d = 3 you make 9 (contribution 2.25). Sum every world times its probability and you get 5.5.
Input: q = 3, demand = [3], probs = [1.0], cost = 2, price = 5, salvage = 0 Output: 9.0
Demand is certain. You buy 3, sell 3: profit = 15 − 6 = 9.
Input: q = 0, demand = [0, 1, 2, 3, 4, 5], probs = [0.05, 0.15, 0.25, 0.25, 0.20, 0.10], cost = 2, price = 5, salvage = 0 Output: 0.0
Ordering nothing costs nothing and sells nothing.
Constraints
Pick an order quantity, then reveal demand one outcome at a time. The running expected value starts at zero and accumulates each contribution P(d) · profit(q, d) — the same sum your function has to return.
| Demand d | P(d) | Sold | Left | Short | Profit | P(d) · profit | Running EV |
|---|
CPython in the browser. Tab indents, or completes from the live kernel (Jedi). Shift+Tab dedents. ⌘/Ctrl+Enter runs the buffer. Names persist across runs until you restart.