0

I use input [0,2,3,4,6,7,8,16,17,18,21,23,24,26,34,35,36,37,38,40,41,46,47]

But output [0,2,6,16,21,23,26,34,40,46] which is wrong Should be [2,6,16,23,34,40,46]

How to find the first number of multiple consecutive sequence in list?

If it is possible, can be editable to find the last one too Such that [4, 8, 18, 24, 38, 41, 47]

def find_consecutive_numbers(lst):
    result = []
    i = 0
    while i < len(lst)-2:
        if lst[i]+1 == lst[i+1] and lst[i+1]+1 == lst[i+2]:
            result.append(lst[i])
            i += 2
        else:
            i += 1
    return result

I had tried to ask chatgpt, but result is not perfect. It use string to do first. But some unexpected numbers in list too

Maiva
  • 13
  • 2

1 Answers1

0

Try grouping by difference to preceding element and yield the first of each group that difference is 1:

from itertools import pairwise, groupby

def find_consecutive_numbers(lst, last=False):
    for k, g in groupby(pairwise(lst), key=lambda x: x[1]-x[0]):
        if k == 1:
            if last:
                *_, (_, end) = g
                yield end
            else:
                yield next(g)[0]

>>> list(find_consecutive_numbers(l))
[2, 6, 16, 23, 34, 40, 46]
>>> list(find_consecutive_numbers(l, last=True))
[4, 8, 18, 24, 38, 41, 47]

Some docs:

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • This is better than chatgpt. However, need to install new python 3.11 in order to use pairwise. Syntax is quite advanced. – Maiva Jun 29 '23 at 14:53
  • @Maiva - ```pairwise``` comes in Python 3.10. And if you don't want to upgrade, you can still write your *own* version too. – Daniel Hao Jun 29 '23 at 14:55
  • @Maiva `pairwise = lambda lst: zip(lst, lst[1:])` for older versions (you could use `itertools.islice` instead of the more spatious list slice). – user2390182 Jun 29 '23 at 16:55