Drill

ProblemsPython › monitoring

Should the alarm go off

mediummonitoringPython

A single spike is noise. An alert only fires when the reading stays over the limit for several samples in a row.

alarm_fires(readings: list<int>, limit: int, in_a_row: int) → bool

Solve it in the editor →

Where you start

def alarm_fires(readings: list[int], limit: int, in_a_row: int) -> bool:
    

Worked examples

CallResult
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

The same problem in another language

More monitoring problems in Python