I've written a function to split a list into several lists with consecutive integers, e.g.:
extract_subsequences([1,2,3,7,8,9])
[[1, 2, 3], [7, 8, 9]]
extract_subsequences([1,2,3])
[[1, 2, 3]]
extract_subsequences([1,2,3, 10])
[[1, 2, 3], [10]]
extract_subsequences([1,2, 4,5, 8,9])
[[1, 2], [4, 5], [8, 9]]
This is the code that I came up with:
import numpy as np
def extract_subsequences(seq):
def split_sequence(seq):
for i in np.arange(1, len(seq)):
if seq[i] != seq[i - 1] + 1:
break
if i < len(seq) - 1:
return seq[:i], seq[i:]
else:
if seq[-1] == seq[-2] + 1:
return seq, []
else:
return seq[:-1], [seq[-1]]
res = []
last = seq
while len(last) > 1:
first, last = split_sequence(last)
res.append(first)
if len(last) == 1:
res.append(last)
return res
Can someone help me improve this code? It's kind of difficult to read with all the indices and special cases, and for the same reasons it was also quite difficult to write. I would very much appreciate a better way of thinking about this problem.