Search code examples
pythonarraysmathnumbersiteration

How to check whether array contains specific amount of consecutive numbers which don't have to be in order?


I need to be able to check whether an array has 3 or more (in my situation precisely 3) numbers in order, i.e. where one is greater by the same number as another is greater than this. For example, I have a list my_list=[9,6,5,1], and I want to indicate that this list has consecutive numbers: 1, 5, 9.


Solution

  • Start by finding all of the differences between all the unique combinations of elements in your list:

    >>> my_list=[9,6,5,1]
    >>> from itertools import combinations
    >>> combos = [(a, b, b - a) for a, b in combinations(sorted(my_list), 2)]
    >>> combos
    [(1, 5, 4), (1, 6, 5), (1, 9, 8), (5, 6, 1), (5, 9, 4), (6, 9, 3)]
    

    Put the diffs into a Counter so you can find the one that repeats the greatest number of times:

    >>> from collections import Counter
    >>> diffs = Counter(c[2] for c in combos)
    >>> best_diff = max(diffs, key=diffs.get)
    >>> best_diff
    4
    

    Now merge all the combos that have that diff and you have the consecutive sequence you want:

    >>> sorted({n for c in combos for n in c[:2] if c[2] == best_diff})
    [1, 5, 9]