Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting sets (not a single set)

I have a number of sets with each set representing the unique items in a single data file. Some of these sets are subsets of others, some are identical.

Is there a primitive or a module that lets me sort the sets such that I get something like

A <= B <= C <= D <= E

et cetera for the sets A, B, C, D, E, F?

I.e. sort not the items from a set, but instead sort the sets themselves by their relation as subsets and supersets of each other?

like image 955
0xC0000022L Avatar asked Feb 12 '23 20:02

0xC0000022L


1 Answers

Just put them in a list and sort them. If a set is a subset of another set their <= relationship is True, and this extends to sorting. In other words, what you want is the default sort order already.

Demo:

>>> A = {1, 2}
>>> B = A | {3}
>>> C = B.copy()
>>> D = C | {4}
>>> A <= D
True
>>> [B, C, D, A]
[set([1, 2, 3]), set([1, 2, 3]), set([1, 2, 3, 4]), set([1, 2])]
>>> sorted([B, C, D, A])
[set([1, 2]), set([1, 2, 3]), set([1, 2, 3]), set([1, 2, 3, 4])]

To be explicit: two sets that are not a subset of the other return False for all ordering operations, and their relative order when sorted won't change. This means that disjoint sets in the sequence will throw a spanner in the works, as they violate the expectation of total ordering sorting has.

like image 148
Martijn Pieters Avatar answered Feb 14 '23 09:02

Martijn Pieters