nums = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7, 8, 7, -1, 0, 1, 182, 181, 180, 179, -1, -2, -3, 5, 6, 6, -8, -7, -6, 2, 4, 6, 12, 15, 18, 15, 12] def find_consecutive_runs(numbers): if not isinstance(numbers, list): raise TypeError(f'`numbers` must be a list, received {type(numbers)}') if not all(isinstance(idx, int) for idx in numbers): raise ValueError(f'`numbers` must be a list of integers') matchedIndices = [] # runSize is how many consecutive numbers we want to find runSize = 3 # increment is the expected distance between numbers, e.g., multiples of 2, 3, etc increment = 1 for idx, num in enumerate(numbers): # find last viable start index based on list length lastStartIndex = len(numbers) - (runSize - 1) # we'll iterate over the list, starting with each subsequent index until we're out of sets if idx < lastStartIndex: endIdx = idx + runSize set = numbers[idx:endIdx] base = set[0] mapped = [] for x, val in enumerate(set): # get the absolute difference between the first number and each number in the list absDiff = abs(val - base) # since we have an absolute number for the difference, # we can just treat this as positively incrementing # as negative numbers will already be handled; # so the expected value at any given index is simply the product of the index # multipled by the increment value, # allowing for generic handling of any increment size # (e.g., idx: 0, inc: 1, idx:1, inc: 1 = 1, idx: 2, inc: 1 = 2) expectedIdxValue = x * increment mapped.append(absDiff == expectedIdxValue) if all(mapped): matchedIndices.append(idx) return matchedIndices if len(matchedIndices) else 'None' result = find_consecutive_runs(nums) print(result)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question