Saturday, July 14, 2018

Sets


Introduction
------------

- an unordered collection of elements
- doesn't have duplicate elements
- to create a set, use `{ elements .. }`
- to create an empty set, use `()`; `{}` is used to create an empty dictionary

Using sets
----------

Creating a set
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>>
Membership testing
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False
>>>
Operations between 2 sets
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in either a or b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
>>>
Creating set comprehension
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}
>>>
Using set() function to remove duplicate
elements
>>>
>>> words = [ x for x in input('Enter words separated by spaces: ').split() ]
Enter words separated by spaces: hello world hello how are you you
>>> words
['hello', 'world', 'hello', 'how', 'are', 'you', 'you']
>>>
>>>
>>> set(words)
{'you', 'how', 'are', 'hello', 'world'}
>>>
Adding and removing elements
>>> s1 = { 1, 3.4, -0.9, 100, 100 }
>>> s1
{-0.9, 1, 3.4, 100}
>>>
>>> s1.add('500')  # adds a single element
>>> s1
{-0.9, 1, 3.4, 100, '500'}
>>>
>>> s1.update([1000, 501, 234])  # adding multiple elements
>>> s1
{-0.9, 1, 3.4, 100, 1000, 234, 500, 501}
>>>
>>> s1.discard(-.09)  # removing an element
>>> s1
{-0.9, 1, 3.4, 100, 1000, 234, 500, 501}
>>> s1.discard(-0.9)
>>> s1
{1, 3.4, 100, 1000, 234, 500, 501}
>>>
>>> s1.clear()  # removes all elements
>>> s1
set()
>>>
Other set modifiers
copy
difference()
difference_method()
remove(el)
union(s)
intersections(s)
isdisjoint()
issubset()
issuperset()
pop()

No comments:

Post a Comment