0

I have a list [1, 3, 4, 6, 8, 9, 10] where in this list, I have two separate sublists of consecutive integers; namely, [3, 4] and [8, 9, 10].

I need to write a function that can return these sublists, such as:

array = [1, 3, 4, 6, 8, 9, 10]
my_func(array)
>>>> [[3, 4], [8, 9, 10]]

I have a working solution, but I wondered if there wasn't something more simplistic?


array = [1, 3, 4, 6, 8, 9, 10]
def my_func(arr):
    found = []
    for idx, elem in enumerate(arr):
        consecutive_elements = [item for sublist in found for item in sublist]
        if elem not in consecutive_elements:

            substring = [elem]
            count = 1
            while idx + count < len(arr):
                if arr[idx + count] == elem + count:
                    substring.append(arr[idx + count])
                    count += 1
                else:
                    break
            if len(substring) > 1:
                found.append(substring)

        else:
            continue

    return found

my_func(array)
>>>> [[3, 4], [8, 9, 10]]
j9000
  • 386
  • 1
  • 3
  • 14

0 Answers0