3 ms·
Gave it another shot: def monotonic(arr): if not arr: return [] new_arr = [] sub_arr = [arr[0]] parity = 0 for n
by alecst 5y ago
Gave it another shot:
def monotonic(arr):
if not arr: return []
new_arr = []
sub_arr = [arr[0]]
parity = 0
for n in arr[1:]:
delta = n - sub_arr[-1]
if parity == 0:
parity += delta
elif parity * delta < 0:
new_arr.append(sorted(sub_arr))
sub_arr = []
parity = 0
sub_arr.append(n)
new_arr.append(sorted(sub_arr))
return new_arr
`delta` keeps track of whether the next element increases or decreases, whereas `parity` keeps track of the parity of the run. No imports, arbitrary iterators, single function.
You can continue to pare it down.