Combining two sets
After this: Work out union, intersection and difference with membership tests, and say what they cost.
On this page · 8 sections · 4 checks
So far you have asked one set about one item. Real questions often involve two sets. Which students take both maths and physics? Who logged in today but not yesterday?
This lesson shows three ways to combine two sets. All three are built from the membership test you already know.
Three ways to combine two sets
Here are two small clubs.
chessholdsamirandbea.musicholdsbeaandkai.
Bea is in both clubs. There are three common questions we can ask.
| Name | Question | Answer for these clubs |
|---|---|---|
| Who is in at least one club? | amir, bea, kai | |
| Who is in both clubs? | bea | |
| Who is in chess but not in music? | amir |
Bea appears once in the union, because a set holds each item once.
A difference has a direction. "In chess but not in music" gives amir, and "in music but not in chess" gives kai. We write these as chess − music and music − chess.
Working it out with membership tests
You can work out each answer with a loop. Here is the intersection of chess and music, one step at a time.
- Start with an empty result.
- Take
amirfromchess. Askmusic: isamirhere? No, so skip him. - Take
beafromchess. Askmusic: isbeahere? Yes, so add her to the result. - There are no more names in
chess. The result holdsbea.
Each of the three operations is a loop like this. Here they are for any two sets a and b.
- Union, a | bunion(a, b). Copy
a, then add each key ofb. A key that is already there is noticed and skipped. - Intersection, a & bintersection(a, b). Go through
aand keep each key thatbcontains. - Difference, a - bdifference(a, b). Go through
aand keep each key thatbdoes not contain. The direction matters, so b - adifference(b, a) is a different set.
Why this is fast
Now take two sets of three keys: a = {cat, act, dog} and b = {act, dog, fox}. Which keys are in both?
Without a hash set, you might compare every key of a with every key of b. That is 3 × 3 = 9 comparisons. With a thousand keys in each, it is 1,000 × 1,000 = one million comparisons.
With a hash set, you make one membership test per key. A membership test costs O(1) on average, which means it takes about the same work however big the set is. So three keys need three tests, and a thousand keys need a thousand tests. That is a thousand tests against a million comparisons.
The code
def union(a, b): result = set(a) # copy a for item in b: # then add every item of b result.add(item) # a repeat is noticed and skipped return result
def intersection(a, b): result = set() for item in a: # one pass over a if item in b: # one membership test per item result.add(item) return result
def difference(a, b): result = set() for item in a: if item not in b: # keep what b lacks result.add(item) return result
a = {"cat", "act", "dog"}b = {"act", "dog", "fox"}print(sorted(union(a, b))) # sorted, so the output is stableprint(sorted(intersection(a, b)))print(sorted(difference(a, b)))['act', 'cat', 'dog', 'fox'] ['act', 'dog'] ['cat']
static Set<String> union(Set<String> a, Set<String> b) { Set<String> result = new HashSet<>(a); // copy a for (String item : b) { // then add every item of b result.add(item); // a repeat is noticed and skipped } return result;}
static Set<String> intersection(Set<String> a, Set<String> b) { Set<String> result = new HashSet<>(); for (String item : a) { // one pass over a if (b.contains(item)) { // one membership test per item result.add(item); } } return result;}
static Set<String> difference(Set<String> a, Set<String> b) { Set<String> result = new HashSet<>(); for (String item : a) { if (!b.contains(item)) { // keep what b lacks result.add(item); } } return result;}
Set<String> a = Set.of("cat", "act", "dog");Set<String> b = Set.of("act", "dog", "fox");System.out.println(new TreeSet<>(union(a, b))); // sorted, so the output is stableSystem.out.println(new TreeSet<>(intersection(a, b)));System.out.println(new TreeSet<>(difference(a, b)));[act, cat, dog, fox] [act, dog] [cat]
Here is how to read it.
unioncopiesaintoresult, then adds every item ofb. An add of a repeat changes nothing.intersectionstarts with an emptyresult. It goes throughaand adds an item only whenbcontains it.differenceis the same loop with the test turned round. It adds an item only whenbdoes not contain it.- The last lines sort the results before printing. A set has no promised order, and sorting makes the output the same on every run.
Watch it happen
The table holds a: cat and act in slot 0, and dog in slot 2. You will ask it about each key of b in turn and count the comparisons. The keys that answer yes are a & bintersection(a, b).
This task goes through b and asks a, while the code above goes through a and asks b. Both give the same answer, because a key that is in both sets is found from either side.
- Contains? actIs act in a? Slot 0 holds a chain of two keys. Count the comparisons.
- Contains? dog
- Contains? fox
- 0catact
- 1—
- 2dog
- 3—
- 4—
- 5—
- 6—
- 7—
Start with the first task above, or try any key.
- count
- 3
- load
- 0.38
- compares
- 0
That was three questions and three comparisons in total. act took two comparisons, because it sits behind cat in its chain. dog took one. fox took none, because slot 5 is empty, so fox was never compared with anything in a.
The cost
Let n be the number of keys in a, and m the number of keys in b.
- Intersection and difference go through
aonce, with one membership test per key. That is n tests, so the cost is O(n) on average. - Union adds every key of both sets. That is n + m adds, so the cost is O(n + m) on average. The work grows with the two sizes added together.
On average the cost is not n × m, because the hash sends each question straight to one slot and one short chain. With a bad hash function, where every key lands in one chain, it could reach n × m.
Check yourself
maths is the set of students taking maths, and physics is the set taking physics. You want the students taking maths but not physics. Which operation do you need?
What does this print?
a = {"cat", "act", "dog"}b = {"act", "dog", "fox"}print(sorted(a & b), len(a | b))Set<String> a = Set.of("cat", "act", "dog");Set<String> b = Set.of("act", "dog", "fox");Set<String> both = new HashSet<>(a); both.retainAll(b);Set<String> union = new HashSet<>(a); union.addAll(b);System.out.println(new TreeSet<>(both) + " " + union.size());What does this print?
a = {"cat", "act", "dog"}b = {"act", "dog", "fox"}print(sorted(b - a))Set<String> a = Set.of("cat", "act", "dog");Set<String> b = Set.of("act", "dog", "fox");Set<String> onlyB = new HashSet<>(b); onlyB.removeAll(a);System.out.println(new TreeSet<>(onlyB));a has n keys and b has m keys. Why does the hand-written intersection cost O(n) and not O(n × m)?
Connect
Both languages have these operations built in.
a = {"cat", "act", "dog"}b = {"act", "dog", "fox"}print(sorted(a | b)) # unionprint(sorted(a & b)) # intersectionprint(sorted(a - b)) # difference: in a, not in bprint(sorted(b - a)) # the other way round['act', 'cat', 'dog', 'fox'] ['act', 'dog'] ['cat'] ['fox']
Set<String> a = Set.of("cat", "act", "dog");Set<String> b = Set.of("act", "dog", "fox");Set<String> union = new HashSet<>(a); union.addAll(b); // unionSet<String> both = new HashSet<>(a); both.retainAll(b); // intersectionSet<String> onlyA = new HashSet<>(a); onlyA.removeAll(b); // difference: in a, not in bSet<String> onlyB = new HashSet<>(b); onlyB.removeAll(a); // the other way roundSystem.out.println(new TreeSet<>(union));System.out.println(new TreeSet<>(both));System.out.println(new TreeSet<>(onlyA));System.out.println(new TreeSet<>(onlyB));[act, cat, dog, fox] [act, dog] [cat] [fox]
- Work out union, intersection and difference by hand, as loops of membership tests.
- Say why the cost on average grows with n + m at most, not with n × m.
- Tell a − b from b − a.