Reputation: 216
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
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