Problems › Python › monitoring
Should the alarm go off
A single spike is noise. An alert only fires when the reading stays over the limit for several samples in a row.
- A sample counts as a breach when it is strictly above the limit.
- The alarm fires as soon as that many breaches happen back to back.
- A run length of zero or less never fires.
alarm_fires(readings: list<int>, limit: int, in_a_row: int) → bool
Where you start
def alarm_fires(readings: list[int], limit: int, in_a_row: int) -> bool:
Worked examples
| Call | Result |
|---|---|
alarm_fires([1, 5, 6, 7, 2], 4, 3) | True |
alarm_fires([1, 5, 2, 6, 7], 4, 3) | False |
alarm_fires([5, 6], 4, 2) | True |
alarm_fires([4, 4, 4], 4, 1) | False |
Hint
One counter, reset to zero the moment a reading comes back inside the limit.
Reference solution in Python
def alarm_fires(readings: list[int], limit: int, in_a_row: int) -> bool:
if in_a_row <= 0:
return False
run = 0
for r in readings:
run = run + 1 if r > limit else 0
if run >= in_a_row:
return True
return False