排序两个关联数组/栈:求当前采购苹果的加权平均时间戳
Alright, let's tackle this problem step by step. Calculating the weighted average timestamp of remaining apple inventory is a great example of applying inventory tracking logic with time-based weighting—perfect for perishable goods like apples where you want to account for how long stock has been held.
The core idea here is to track individual purchase batches, apply sales against those batches (using FIFO logic—standard for perishables, since you sell older stock first), then compute a weighted average of the remaining batches' timestamps (weighted by the quantity left in each batch).
Step 1: Prepare and Normalize Data
First, get your data in a usable format:
- Convert all epoch timestamp strings to numeric integers (we'll need to do arithmetic with them)
- Sort purchase data by timestamp (ascending order—so we process the oldest stock first)
- If your sales data includes timestamps, sort those too; if not, assume sales are applied in chronological order of purchases.
Step 2: Track Inventory Batches with FIFO
Let's use a concrete example to make this tangible:
Sample Data
Purchases:
| Epoch Timestamp | Quantity |
|---|---|
| 1690000000 | 10 |
| 1690100000 | 15 |
| 1690200000 | 20 |
Sales:
| Quantity |
|---|
| 12 |
| 18 |
Processing Sales
- First sale (12 apples):
- Take all 10 from the oldest batch (1690000000), then 2 from the second batch (1690100000). Remaining batches:
- Batch 2: 15 - 2 = 13 apples
- Batch 3: 20 apples
- Take all 10 from the oldest batch (1690000000), then 2 from the second batch (1690100000). Remaining batches:
- Second sale (18 apples):
- Take all 13 from batch 2, then 5 from batch 3. Remaining batches:
- Batch 3: 20 - 5 = 15 apples
- Take all 13 from batch 2, then 5 from batch 3. Remaining batches:
Step 3: Compute Weighted Average Timestamp
Use this formula for the weighted average:Weighted Average = (Sum of (Timestamp * Remaining Quantity for each batch)) / (Total Remaining Quantity)
For our example:
- Total remaining = 15
- Sum =
1690200000 * 15 - Weighted average = 1690200000 (makes sense since only the newest batch is left)
Another example with multiple remaining batches:
If we had 5 apples left from batch 2 (1690100000) and 10 from batch 3 (1690200000):
- Sum =
(1690100000 *5) + (1690200000 *10) = 25352500000 - Total remaining =15
- Weighted average =
25352500000 /15 ≈ 1690166666.67
Step 4: Practical Code Implementation (Python)
Here's a reusable snippet to implement this logic:
def calculate_weighted_avg_timestamp(purchases, sales): # Normalize purchases: convert timestamps to integers, sort by date sorted_purchases = sorted([(int(ts), qty) for ts, qty in purchases], key=lambda x: x[0]) remaining_batches = sorted_purchases.copy() # Apply each sale to the inventory (FIFO) for sale_qty in sales: remaining_sale = sale_qty i = 0 while remaining_sale > 0 and i < len(remaining_batches): batch_ts, batch_qty = remaining_batches[i] if batch_qty <= remaining_sale: # Take entire batch to fulfill the sale remaining_sale -= batch_qty remaining_batches.pop(i) else: # Take only what's needed from the batch remaining_batches[i] = (batch_ts, batch_qty - remaining_sale) remaining_sale = 0 # Calculate the weighted average total_weighted_ts = 0 total_remaining = 0 for ts, qty in remaining_batches: total_weighted_ts += ts * qty total_remaining += qty return total_weighted_ts / total_remaining if total_remaining > 0 else None # Example usage purchases = [ ("1690000000", 10), ("1690100000", 15), ("1690200000", 20) ] sales = [12, 18] avg_timestamp = calculate_weighted_avg_timestamp(purchases, sales) print(f"Weighted average epoch timestamp: {avg_timestamp}")
Key Notes
- FIFO vs. Other Methods: I used FIFO here because it's the most logical for perishables, but if you need LIFO (sell newest stock first), just reverse the order of the sorted purchase batches.
- Sale Timestamps: If your sales include timestamps, add a check to only apply sales against batches that were purchased before the sale date.
- Edge Cases: The code handles empty inventory (returns
None) and partial batch sales out of the box.
内容的提问来源于stack exchange,提问作者CQM

