Problem 312357 · easy · Level 03 Linear Management & Searching

Three High Readings in a Row

py-iterators · enumerate · early exit

A river gauge reports the water level every few minutes. The flood service raises the alarm when the level has been strictly above limit for k readings in a row. The gauge never stops reporting, so the readings arrive as a stream that may be endless.

Write flood_alarm(levels, limit, k) that returns the position (counting from 0) of the reading at which the alarm goes off, that is, the k-th consecutive reading above limit. If the stream ends before that happens, return None.

Two helpers build the tests' streams and are available with Run: stream(values) hands out a list's values one at a time, and gauge(seed) is an endless generator of simulated levels.

Examples

Input:  levels = stream([2.0, 3.1, 3.4, 2.9, 3.2, 3.3, 3.5, 3.0]), limit = 3.0, k = 3
Output: 6
Explanation: 3.1 and 3.4 are only two in a row. 3.2, 3.3 and 3.5 (positions 4, 5, 6) are three.

Input:  levels = stream([3.5, 3.0, 3.6]), limit = 3.0, k = 2
Output: None
Explanation: 3.0 is not strictly above the limit, so the run restarts.

Constraints

  • 1 <= k <= 1000; levels may be endless, and then the alarm is guaranteed to go off.
  • The stream can be read only once, from the front.

Goals

  • Process a stream that may never end, one item at a time
  • Stop reading as soon as the answer is known
  • Keep only the small state the question needs (the length of the current run)
Starting Python…