Jennis
Jennis

Reputation: 11

Finding consecutive numbers in seperate arrays

If I have an array of arrays of numbers e.g. [[0, 5, 6, 11], [8, 9, 12], [7, 10, 13]]

how do I find numbers that are consecutive with one from each array? So I would like my output to be [11,12,13]

Also I need it to be flexible to number of arrays and length of arrays.

I found this solution:

def find_continuous_items(data):
    for p in product(*data):
        if all(b-a==1 for a, b in zip(p, p[1:])):
            yield p

however, the problem is my arrays can be very long, resulting in this solution being computationally too slow. Is there any solution that won't take an incredibly long amount of time?

Upvotes: 1

Views: 50

Answers (1)

ILS
ILS

Reputation: 1380

You don't need to make cartesian product of all you sublists. You can loop through your first sublist, then check the remainding sublists for subsequent numbers.

Like this,

nested_lst = [[0, 5, 6, 11], [8, 9, 12], [7, 10, 13]]
num_sublst = len(nested_lst)
result = []  # all consecutive number lists we will find
for v in (nested_lst[0] if num_sublst else []):
    found = True
    for i in range(1, num_sublst):
        if v+i not in nested_lst[i]:
            found = False
            break
    if found:
        result.append([v + i for i in range(num_sublst)])
print(result)
# [[11, 12, 13]]

Further, if querying in lists cost too much, you can convert them to sets first.

Upvotes: 2

Related Questions