Search code examples
pythonlistfunctional-programmingfilteringpurely-functional

More pythonic way of filtering out stable values in a list


I wrote a function that allows me to run through a list, compare the values with the predecessors, and assert at which point the list becomes "stable" for a certain amount of entries. The values in the list represent a signal, that may or not reach a stable point. I came up with this:

def unstableFor(points, maxStable):
    count = 0;
    prev = points[0]
    for i in range(1, len(points)):
        if points[i] == prev:
            count = count + 1
        else:
            count = 0
            prev = points[i]
        if count >= maxStable:
            return i
    return len(points) - 1

The returned value is then used by the caller for cutting away the last part of the list.

It does its job, however, I am quite dissatisfied with how cumbersome it looks. Can you think of a more pythonic, possibly purely-functional way of performing this filtering operation?


Solution

  • Use enumerating and zipping:

    def unstableFor (points, threshold):
        for i, (a, b) in enumerate(zip(points, points[1:])):
            count = count + 1 if a == b else 0
            if count >= threshold:
                return i
        return i