Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping integers by set membership in Python

Working in Python, given a list of N sets of integers from the range range(s,n), how can I build a list that groups all these integers according to their set memberships? An example is really going to help me explain here:

Example input (N=2 sets):

integerRange = range(0,13)
input = [set([0,1,2,3,7,8,9,12]), set([0,1,2,3,4,5,6,12])]

Desired output:

out = [set([10,11]), set([4,5,6]), set([7,8,9]), set([0,1,2,3,12])]

So in the output each integer in range(s,n) appears exactly once, and there are 2^N sets. In the example, out[0] contains the integers that are in neither set. out[1] contains the integers that are in the second set but not the first. out[2] contains the integers that in the first set but not the second. And finally out[3] contains the integers that are common to both sets.

For 2 sets this is fairly easy... but I'm stumped for N sets. Does anyone have a clue?

like image 801
Spacecookies Avatar asked Nov 18 '25 22:11

Spacecookies


1 Answers

I cringe even thinking about the efficiency of this, but it's pretty compact:

 out = [set(range(x, y))]
 for in_set in input:
    out_diff = [out_set - in_set for out_set in out]
    out_union = [out_set & in_set for out_set in out]
    out = out_diff + out_union
like image 83
Tim Yates Avatar answered Nov 20 '25 12:11

Tim Yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!