Skip to content

Conversation

@rhettinger
Copy link
Contributor

Add a slightly improved version of running_median() which was recently added to the CPython docs.

@bbayles
Copy link
Collaborator

bbayles commented Aug 1, 2025

Interesting! I thought this would use the ideas in your classic blog post. This is a very elegant alternative.

@bbayles bbayles merged commit 306aa37 into more-itertools:master Aug 1, 2025
6 checks passed
@rhettinger
Copy link
Contributor Author

The running median in the blog post needed an indexable skiplist (or sorted collections or a blist) because it was the median over a window instead of all values seen so far. Windowing requires the ability to delete old elements as well as add new ones, and the heap version can't do that (it is add only).

If you're open to going beyond what is in the CPython docs, it would be nice to add an option for a running median over a sliding window:

def running_median(iterable, *, window=None):
    """Cumulative median of values seen so far or values in a sliding window.

    For example:

        >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0]))
        [5.0, 7.0, 5.0, 7.0, 8.0, 8.5]
        >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0], window=3))
        [5.0, 9.0, 8.0, 7.0, 8.0, 9.0]

    Supports numeric types such as int, float, Decimal, and Fraction,
    but not complex numbers which are unorderable.
    """

@bbayles
Copy link
Collaborator

bbayles commented Aug 1, 2025

Yeah, let's do the windowed version - would be nice to be able to do a very long running median.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants