-1

リストがあれば

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

以下に示すように、3 つのジグザグを取得したいと考えています。ジグザグは、局所的な最大値 (高原になる可能性があります) と最小値 (谷になる可能性があります) として定義されます。A、B、C の 3 つのジグザグがあります。と B は台地で重なり、B と C は谷で重なります

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

ここに画像の説明を入力

4

1 に答える 1

1

一般的な Python のソリューションですl。 は任意のイテレータにすることができ、1 回だけスキャンされることに注意してください。

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]]
于 2013-08-14T01:42:47.350 に答える