[Solved] How can we test if a list contains n consecutive numbers with a difference of 1? [closed]


Try reducing your list.

from functools import reduce


def get_all_consecutives(iterable, consecutive_limit):
    consecutives = []

    def consecutive_reducer(accumulator, next_item):
        if not accumulator:
            accumulator.append(next_item)
        else:
            if next_item - accumulator[-1] == 1:
                accumulator.append(next_item)
            else:
                accumulator = [next_item]

        if len(accumulator) == consecutive_limit:
            consecutives.append(accumulator)

        return accumulator

    reduce(consecutive_reducer, iterable, [])

    if not consecutives:
        return False
    elif len(consecutives) == 1:
        return consecutives[0]
    else:
        return consecutives


iterable = [10, 19, 5, 6, 7, 8, 2, 7, 10, 12]
consecutives = get_all_consecutives(iterable, 4)
print(consecutives)  # [5, 6, 7, 8]

iterable = [5, 2, 12, 10, 11, 12, 14, 95]
consecutives = get_all_consecutives(iterable, 5)
print(consecutives)  # False

iterable = [8, 10, 50, 10, 11, 12, 8, 9, 40, 41, 42]
consecutives = get_all_consecutives(iterable, 3)
print(consecutives)  # [[10, 11, 12], [40, 41, 42]]

solved How can we test if a list contains n consecutive numbers with a difference of 1? [closed]