Sunday, January 21, 2007

Python Sets

http://www.linuxforums.org/programming/introduction_to_python__part_1.html
Sets

I think I don't really have to explain what a set is, as everyone should know them from mathematics. It's simply a pile of elements that do not have ordering and do not contain duplicates.

A set has to be initialized with the elements of a list. Since you already know what a list is, we do this in one step. Just like with dictionaries, print can handle a set as it is.
Once we have a set, I show he first useful feature of sets: testing whether an element is in the set.

inventory_carpenter=set(['helmet', 'gloves', 'hammer'])
print inventory_carpenter # outputs set(['helmet', 'hammer', 'gloves'])

print 'gloves' in inventory_carpenter # outputs 'True'

Since sets are interesting only if we have more that one of them, let's introduce another one! Once we have that, we can immediately see what are the elements that both sets contain (intersection).

inventory_highscaler=set(['helmet', 'rope', 'harness', 'carabiner'])

print inventory_carpenter & inventory_highscaler # outputs 'set(['helmet'])'

Similarly, we can have the union of sets ( using | ), difference ( using - ), or symmetric difference (using ^).
For sets, you don't really need anything else, as you can do every meaningful operation using the ones above. For example, to add a new element, you can use union.

inventory_carpenter = inventory_carpenter | set(['nails'])

No comments: