15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using Sets 335<br />

Bill Evans John Doe<br />

Bo Biggs<br />

Mary Jacobs<br />

John Doe<br />

Figure 2-3:<br />

Intersection<br />

takes only<br />

data<br />

common in<br />

both sets<br />

and stores<br />

that data in<br />

a third set.<br />

John Doe<br />

Now if you wanted to find only that data stored in both sets, you could use<br />

the intersection command to store this data in a third set, as follows:<br />

Book III<br />

Chapter 2<br />

newset = clubmembers.intersection(politicians)<br />

This creates a third set — newset — which contains the name John Doe.<br />

The other names are omitted because they aren’t in both original sets.<br />

Combining the different elements of two sets<br />

into a third set with the difference command<br />

If you have two sets, you might want to identify all the data stored in one set<br />

that isn’t stored in a second set. To do this, you’d use the difference command,<br />

as shown in Figure 2-4.<br />

Sets and<br />

Linked Lists<br />

To use the difference command in Python, you need to identify the two<br />

set names with the difference command. Suppose you had one set called<br />

clubmembers and another set called politicians, as follows:<br />

from sets import Set<br />

clubmembers = Set([‘Bill Evans’, ‘John Doe’, ‘Mary Jacobs’])<br />

politicians = Set ([‘Bo Biggs’, ‘John Doe’])

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!