Angelika
Angelika

Reputation: 216

Find intersecting set between two ranges

I have two sets given by boundaries.
For example:

set1_bounds = (1, 5)
set2_bounds = (2, 8)

Exactly real sets are:

set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4, 5, 6, 7, 8}

Now for checking if these sets intersect, I create these sets using bounds and do following:

set1 = {i for i in range(set1_bounds[0], set1_bounds[1]+1)}
set2 = {i for i in range(set2_bounds[0], set2_bounds[2]+1)}
intersect = set.intersection(set1, set2)

But I think memory complexity (and computational too) is not the most optimal.

How should I do this correctly?

Upvotes: 1

Views: 252

Answers (1)

yatu
yatu

Reputation: 88236

No need to generate both sets of ranges. Find the range of overlap, and generate a set from it:

r = max(set1_bounds[0], set2_bounds[0]), min(set1_bounds[1]+1, set2_bounds[1]+1)
set(range(*r))
# {2, 3, 4, 5}

Upvotes: 4

Related Questions