开发者

Grouping integers by set membership in Python

开发者 https://www.devze.com 2023-03-06 12:26 出处:网络
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

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 examp开发者_JAVA技巧le, 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?


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号