In Python, given a list of sorted integers, I would to group them by consecutive values and tolerate gaps of 1.
For instance, given a list my_list
:
In [66]: my_list
Out[66]: [0, 1, 2, 3, 5, 6, 10, 11, 15, 16, 18, 19, 20]
I would like the following output:
[[0, 1, 2, 3, 5, 6], [10, 11], [15, 16, 18, 19, 20]]
Now, if I didn't have to tolerate gaps of 1, I could apply the neat solution explained here:
import itertools
import operator
results = []
for k, g in itertools.groupby(enumerate(my_list), lambda (i,x):i-x):
group = map(operator.itemgetter(1), g)
results.append(group)
Is there a way to incorporate my extra requirement in the above solution? If not, what's the best way to tackle the problem?
Numpy is a very useful tool, and not very difficult to learn.
This problem is solvable in
O(n)
with a single line of code (excluding imports, data, and converting to list - if you really need it):More importantly, the code is very fast if you need to process large lists, unlike a pure-python solution
An O(nlogn) solution (assuming the input list isn't sorted) is to first the sort the list you're given, then iterate through each value, creating a new group whenever the difference between the current value and the previous value is at least 3.
Demo
Remember, groupby in itself, is pretty lame. The strength of
itertools.groupby
is the key. For this particular problem, you need to create an appropriate key with memory (stateless key will not work here).Implementation
Object
How it Works
Every time, a new sub-list needs to be created (
curr - prev > threshold
), you toggle a flag. There are different ways to toggle a flagflag = 1; flag *= -1
flag = [0, 1 ]; flag = flag[::-1]
flag = 0; flag = 0 if flag else 1
Choose what ever your heart contends
So this generates an accompanying key along with your list
Now as
itertools.groupby
, groups consecutive elements with same key, all elements with keys having consecutive0
s or1
s are grouped togetherAnd your final result would be
I generally use
zip
when I want to deal with consecutive elements, and you can useislice
you want to avoid building the list slice:Note that in Python 2.x, you need to use
itertools.izip
to avoid building the list of 2-tuples(current, next_)
.When in doubt you can always write your own generator:
demo:
Here's what I came up with. There's a bit of verbose initialization but it gets the job done. =)