I have a sorted list of integers and I find want find to the number runs in this list. I have seen many examples when looking for numbers runs that increment by 1, but I also want to look for number runs where the difference between numbers is customizable.
For example, say I have the following list of numbers:
nums = [1, 2, 3, 6, 7, 8, 10, 12, 14, 18, 25, 28, 31, 39]
Using the example found here, I'm able to find the following number runs:
[[1, 2, 3], [6, 7, 8], [10], [12], [14], [18], [25], [28], [31], [39]]
However, I want to look for number runs where the difference between two numbers could be more than just 1. For example, I want all number runs with a distance of less than or equal to 2.
[[1, 2, 3], [6, 7, 8, 10, 12, 14], [18], [25], [28], [31], [39]]
Or maybe I want all number runs with a distance of less than or equal to 3.
[[1, 2, 3, 6, 7, 8, 10, 12, 14], [18], [25, 28, 31], [39]]
Here is the function that I'm working with now to get number runs with a distance of 1.
def runs(seq, n):
result = []
for s in seq:
if not result or s != result[-1][-1] + n:
# Start a new run if we can't continue the previous one.
result.append([])
result[-1].append(s)
return result
With the current function, if I set n=1
, then I find all consecutive number sequences. If I set n=2
, then I only find [8, 10, 12, 14]
. How can I modify this function to find number runs that are less than or equal to n
?
I want to be able to do this:
runs(num, 2)
[[1, 2, 3], [6, 7, 8, 10, 12, 14], [18], [25], [28], [31], [39]]