jk1093 - 1 year ago 43

Python Question

I have a list of numbers that looks like this:

`>>>a = [1, 2, 3, 6, 9, 10]`

>>>b = func(a)

>>>print(b)

[(1,2,3), (6,), (9,10)]

basically what I'm looking for is tuples of all runs of consecutive numbers. What would be the fastest way to do this?

Answer

Here's a custom generator:

```
def yield_adjacent(lst):
it = iter(lst)
sub = [next(it)]
while True:
try:
n = next(it)
except StopIteration:
yield tuple(sub)
raise
if n - sub[-1] == 1:
sub.append(n)
else:
yield tuple(sub)
sub = [n]
```

Demo:

```
>>> a = [1, 2, 3, 6, 9, 10]
>>> list(yield_adjacent(a))
[(1, 2, 3), (6,), (9, 10)]
>>> a = []
>>> list(yield_adjacent(a))
[]
>>> a = [1, 3]
>>> list(yield_adjacent(a))
[(1,), (3,)]
>>> a = [1, 3, 4, 9]
>>> list(yield_adjacent(a))
[(1,), (3, 4), (9,)]
```

edit: `for`

loop version:

```
def yield_adjacent(lst):
it = iter(lst)
sub = [next(it)]
for n in it:
if n - sub[-1] == 1:
sub.append(n)
else:
yield tuple(sub)
sub = [n]
yield tuple(sub)
```

Source (Stackoverflow)