Re:Pythonic monotonic
by eesmith on Friday August 13, 2021 @10:41AM
(#28169477)
My updated version is more like a state machine. Your function and mine give the same answers both with the manual test cases and with a cross-comparison using random inputs:
[ Parent
| on HN ]
I came up with a similar solution; using True/None/False instead of 1/0/-1 allows for more self-documenting code
def monotonics(seq):
run = []
last_v = None
increasing = None
for v in seq:
if last_v is None:
pass
elif increasing is None:
if v != last_v:
increasing = v > last_v
elif increasing:
if v < last_v:
increasing = None
yield run
run = []
else:
if v > last_v:
increasing = None
yield run[::-1]
run = []
last_v = v
run.append(v)
if run:
yield run
and, I'd add a two more test cases: [], and [1, 2, 3, 1, 2, 3]