py-13-windowed-aggregator
1.000
Proposed solution
I'll implement the `WindowedAggregator` class according to the specifications.
```python
class WindowedAggregator:
def __init__(self, window: float):
"""window = length of the time window (same units as timestamps)."""
self.window = window
# Store events by group, each group has a list of (timestamp, value) tuples
self.groups = {}
def add(self, ts: float, group: str, value: float) -> None:
"""Record an event. Events may arrive OUT OF ORDER (ts not monotonic)."""
if group not in self.groups:
self.groups[group] = []
self.groups[group].append((ts, value))
def stats(self, group: str, at: float) -> dict:
"""Aggregate the events of `group` whose timestamp is in the half-open
window (at - window, at] — i.e. at-window < ts <= at."""
# If group doesn't exist, return empty stats
if group not in self.groups:
return {"count": 0, "sum": 0.0, "min": None, "max": None, "mean": None}
# Get all events for this group
events = self.groups[group]
# Filter events that fall within the window (at - window, at]
window_start = at - self.window
filtered_events = [(ts, value) for ts, value in events if window_start < ts <= at]
# Calculate statistics
count = len(filtered_events)
if count == 0:
return {"count": 0, "sum": 0.0, "min": None, "max": None, "mean": None}
values = [value for ts, value in filtered_events]
total_sum = sum(values)
min_value = min(values)
max_value = max(values)
mean_value = total_sum / count
return {
"count": count,
"sum": total_sum,
"min": min_value,
"max": max_value,
"mean": mean_value
}
```
This implementation:
1. Stores events in a dictionary where keys are groups and values are lists of (timestamp, value) tuples
2. Allows out-of-order ingestion by simply appending events to the appropriate group's list
3. For `stats()`, filters events based on the half-open window condition (at - window < ts <= at)
4. Calculates all required statistics: count, sum, min, max, and mean
5. Handles edge cases like unknown groups and empty windows correctlyTest output (stdout)
............. [100%] 13 passed in 0.02s
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.