Model Series.rolling(k).mean(), the moving average used to smooth time series, including how it treats missing values.
What to build
A program that prints a rolling mean.
Requirements
- For each position, the result is the mean of the window of the last k values ending there, printed with two decimals.
- With the default
min_periods(equal to k), the result isNaNwhen the window has fewer than k values (the first k - 1 positions) or holds a missing value. Withmin_periods Mgiven, the mean of the window's present values is used when at least M are present, andNaNotherwise. - Print
LABEL: RESULTfor each position.
Input
Line 1: k and optionally M. Line 2: n. Then n lines LABEL VALUE, where VALUE is a number or NaN.
Output
n lines.
Constraints
1 ≤ k ≤ n ≤ 100; 1 ≤ M ≤ k.
Example
Input:
3
5
d1 1
d2 2
d3 3
d4 4
d5 5
Output:
d1: NaN
d2: NaN
d3: 2.00
d4: 3.00
d5: 4.00
Why it works
A rolling window looks back k positions from each row, and min_periods decides how many real values a window needs, which is how pandas keeps a few gaps from wiping out a whole moving average.
Examples
3 5 d1 1 d2 2 d3 3 d4 4 d5 5
d1: NaN d2: NaN d3: 2.00 d4: 3.00 d5: 4.00
2 4 a 10 b NaN c 30 d 40
a: NaN b: NaN c: NaN d: 35.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For each position i, the window is the values from i - k + 1 to i.
Hint 2
By default a window with fewer than k values, or with a missing value, gives NaN (min_periods equals the window size).
Solution
Show one correct solution (try it yourself first)
parts = input().split()
k = int(parts[0])
min_periods = int(parts[1]) if len(parts) > 1 else k
n = int(input())
labels = []
values = []
for _ in range(n):
label, value = input().split()
labels.append(label)
values.append(None if value == "NaN" else float(value))
for i in range(n):
window = values[max(0, i - k + 1) : i + 1]
present = [v for v in window if v is not None]
if len(present) >= min_periods:
print(f"{labels[i]}: {sum(present) / len(present):.2f}")
else:
print(f"{labels[i]}: NaN")