Cumulative median of values seen so far or values in a sliding window. Set *maxlen* to a positive integer to specify the maximum size of the sliding window. The default of *None* is equivalent to an unbounded window. For example: >>> list(running_median([5.0, 9.0, 4.0, 12
(iterable, *, maxlen=None)
| 1382 | |
| 1383 | |
| 1384 | def running_median(iterable, *, maxlen=None): |
| 1385 | """Cumulative median of values seen so far or values in a sliding window. |
| 1386 | |
| 1387 | Set *maxlen* to a positive integer to specify the maximum size |
| 1388 | of the sliding window. The default of *None* is equivalent to |
| 1389 | an unbounded window. |
| 1390 | |
| 1391 | For example: |
| 1392 | |
| 1393 | >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0])) |
| 1394 | [5.0, 7.0, 5.0, 7.0, 8.0, 8.5] |
| 1395 | >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0], maxlen=3)) |
| 1396 | [5.0, 7.0, 5.0, 9.0, 8.0, 9.0] |
| 1397 | |
| 1398 | Supports numeric types such as int, float, Decimal, and Fraction, |
| 1399 | but not complex numbers which are unorderable. |
| 1400 | |
| 1401 | On version Python 3.13 and prior, max-heaps are simulated with |
| 1402 | negative values. The negation causes Decimal inputs to apply context |
| 1403 | rounding, making the results slightly different than that obtained |
| 1404 | by statistics.median(). |
| 1405 | """ |
| 1406 | |
| 1407 | iterator = iter(iterable) |
| 1408 | |
| 1409 | if maxlen is not None: |
| 1410 | maxlen = _index(maxlen) |
| 1411 | if maxlen <= 0: |
| 1412 | raise ValueError('Window size should be positive') |
| 1413 | return _running_median_windowed(iterator, maxlen) |
| 1414 | |
| 1415 | if not _max_heap_available: |
| 1416 | return _running_median_minheap_only(iterator) # pragma: no cover |
| 1417 | |
| 1418 | return _running_median_minheap_and_maxheap(iterator) # pragma: no cover |
| 1419 | |
| 1420 | |
| 1421 | def _windowed_running_mean(iterator, n): |
searching dependent graphs…