如果我有清单
l = [0, 0, 1, 2, 2, 2, 1, -1, -1, -1, 0]
我希望获得三个之字形,一个之字形定义为局部最大值(可以是高原)和最小值(可以是山谷),如下图,有3个之字形,A,B,C而A和B在高原重叠,B和C在山谷重叠
A = [0, 0, 1, 2, 2, 2]
B = [2, 2, 2, 1, -1, -1, -1]
C = [-1, 0]
一般 Python 中的一个解决方案,注意l
可以是任何迭代器,并且它只被扫描一次。
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]]