Question

If I have a list

l = [0, 0, 1, 2, 2, 2, 1, -1, -1, -1, 0]

I hope to obtain three zig-zag, a zig-zag is defined as local maxima (can be a plateau) and minima (can be a valley), as shown below, there are 3 zig zags, A, B, C while A and B overlap in the plateau, B and C overlap in the valley

A = [0, 0, 1, 2, 2, 2]
B = [2, 2, 2, 1, -1, -1, -1]
C = [-1, 0]

enter image description here

No correct solution

OTHER TIPS

A solution in general Python, note that the l can be any iterator, and it is scanned only once.

l = [0, 0, 1, 2, 2, 2, 1, -1, -1, -1, 0]

def zigzag(l):
    if not l:
        return []

    last = l[0]

    # the elements in current rise    
    current_rise = []

    # the elements in current drop
    current_drop  = []

    # return value
    zigzags = []

    # iterate over elements
    for i in l:
        # if we are growing...
        if i > last:
            # and the current_drop is longer than
            # current rise, then we just stopped a drop
            if len(current_drop) > len(current_rise):
                zigzags.append(current_drop)

            # in any case, a new drop can start here.
            current_drop = [i]

        else:
            # else just accumulate a current drop
            current_drop.append(i)

        # same for the other direction
        if i < last:
            if len(current_rise) > len(current_drop):
                zigzags.append(current_rise)

            current_rise = [i]

        else:
            current_rise.append(i)

        last = i

    # add the final segment    
    if len(current_rise) > len(current_drop):
        zigzags.append(current_rise)
    else:
        zigzags.append(current_drop)

    return zigzags

print zigzag(l)
# result [[0, 0, 1, 2, 2, 2], [2, 2, 2, 1, -1, -1, -1], [-1, -1, -1, 0]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top