Tuesday, 13 August 2013

Sets continued...

I will let you figure out this one.  You should note that sets are unordered collections of data and if you want to sort an output you need to convert the set back to a list.  Here are some example of set operations.

>>> a = set( ["a","b","c"] )
>>> b = set( ["b","c","d"] )  #convert two lists to sets
>>> print a.difference(b)
set(['a'])
>>> print b.difference(a)
set(['d'])
>>> print a.union(b)
set(['a', 'c', 'b', 'd'])
>>> print a.intersection(b)
set(['c', 'b'])
>>> print a.symmetric_difference(b)
set(['a', 'd'])
>>> print a
set(['a', 'c', 'b'])
>>> c = list(a)
>>> c.sort()
>>> c
['a', 'b', 'c']
>>>

No comments:

Post a Comment