简体   繁体   中英

Finding a sequence of alternating numbers in a list

I'm currently trying to implement the Fourth Nelson rule from: https://en.wikipedia.org/wiki/Nelson_rules

Ie given a list of numbers of length N, I want to know if there exists a consecutive sequence of numbers that are alternating in direction of length n. 'Alternating' means consecutive numbers go up, then down, then up, etc.

My data is in (t,x) tuples. 't' stands for the time axis, always increasing. 'x' is the value associated with the time and the series we are concerned with. For example:

data = [(0, 2.5), (1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]

Here, the alternating x value sequence is for everything but the first tuple. See the below graph: 红色交替顺序

The alternating sequence is highlighted in red. The rule looks for 14 points in a row, but I want to generalize this to n-points in a row. (n < N) I can't just output True or False, I want to output the tuple of points that satisfy the condition. In other words, the output would be:

outliers = [(1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]

I've tried a few things, none of which resulted in the desired output. These included things like np.diff() and np.sign(). I have a feeling itertools() can do this, but I can't quite get there.

Any input is greatly appreciated.

Here's a first cut at your algorithm in straight Python:

data = [(0, 2.5), (1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]
n = 5

t0, x0 = data.pop(0)
outliers = []
up = bool(x0 > 0)

for t, x in data:
    if (x < x0 and up) or (x > x0 and not up):
        if not outliers:
            outliers = [(t0,x0)]
        outliers.append((t,x))
        up = not up
    else:
        if len(outliers) >= n:
            print 'outliers =', outliers
        outliers = []
    t0,x0 = t,x

if len(outliers) >= n:
    print 'outliers =', outliers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM