|
If-statements are for the weak :-) This uses numpy, but it's the shortest answer presented thus far. In [1]: from itertools import chain, zip_longest
...: import numpy as np
...:
...: def f(l):
...: a = np.array([-np.inf, *l])
...: up = a[:-1] <= a[1:]
...:
...: pos = (up[1:] != up[:-1]).nonzero()[0]
...: pos = [0, *(1+pos), len(l)]
...:
...: up_runs = (l[x:y] for x,y in zip(pos[0::2], pos[1::2]))
...: down_runs = (l[y-1:x-1:-1] for x,y in zip(pos[1::2], pos[2::2]))
...:
...: pairs = zip_longest(up_runs, down_runs)
...: return [*filter(None, chain(*pairs))]
...:
...: f([1, 2, 3, 2, 1, 4, 5, 6, 7])
Out[1]: [[1, 2, 3], [1, 2], [4, 5, 6, 7]]
|