没有重叠的单调:
此版本查找单调序列并且不记录重叠;很抱歉最初没有注意。
def find_sequences(lst, min_len=3):
curr = []
asc = None
for i in lst:
if not curr or len(curr) == 1 or asc and i >= curr[-1] or not asc and i <= curr[-1]:
if len(curr) == 1:
asc = curr[-1] < i
curr.append(i)
else:
if len(curr) >= min_len:
yield curr
asc = None
curr = [i]
if len(curr) >= min_len:
yield curr
产量:
[[0, 1, 3, 8, 10, 13, 13], [11, 5, 1, 0]]
性能:
In [6]: timeit list(find_sequences(x))
100000 loops, best of 3: 8.44 µs per loop
有重叠的单调/非单调:
此函数查找单调和重叠的序列;>=
您可以通过分别更改和<=
来>
轻松地将其更改为非单调工作<
,甚至可以使其参数化。
def find_sequences(lst, min_len=3):
asc, desc = [], []
for i in lst:
if not asc or i >= asc[-1]:
asc.append(i)
else:
if len(asc) >= min_len:
yield asc
asc = [i]
if not desc or i <= desc[-1]:
desc.append(i)
else:
if len(desc) >= min_len:
yield desc
desc = [i]
if len(desc) >= min_len:
yield desc
if len(asc) >= min_len:
yield asc
产量:
[[0, 1, 3, 8, 10, 13, 13], [13, 13, 8, 4], [11, 5, 1, 0]]
性能:
In [3]: timeit list(find_sequences(x))
100000 loops, best of 3: 10.5 µs per loop