Download Python Sets, Dictionaries and Complexity | CSCI 553 and more Exams Computer Systems Networking and Telecommunications in PDF only on Docsity!
CSCI 553: Networking III
Unix Network Programming
Spring 2007
Python Sets, Dictionaries and Complexity
Introduction
The world is not made of lists
Just because it's the first data structure you
meet, doesn't make it the right one for every
task
This lecture introduces two other
fundamental data structures
Allow you to create programs that are simpler
and more efficient
Also look at what “efficient” really means
Set Operations
(^) Like other objects, sets have methods
Many of which can be expressed using operators as well
lows | odds set([0, 1, 2, 3, 4, 5, 7, 9]])
union Create a set with elements that are in either argument lows.union(odds)
lows ^ odds set([0, 2, 4, 5, 7, 9]]) lows.symmetric_diff
Create a set with elements that are in exactly one set erence(odds)
symmetric_diff erence lows is now set([1, 2, 3, 4]])
remove Remove an element from a set lows.remove(0) None
False lows >= odds lows.issuperset(odd
Does one set contain all of another's elements? s)
issuperset
issubset Are all of one set's elements contained in another? lows.issubset(ten) True lows <= ten
set([1, 3]]) lows & odds lows.intersection(od
Create a set with elements that are in both arguments ds)
intersection lows - odds set([0, 2, 4]]) lows.difference(odds )
Create a set with elements that are in one set, but not
the other
difference
clear Remove all elements from the set lows.clear() None lows is now set()
lows is now set([0, 1, 2, 3, 4, 9]])
add Add an element to a set lows.add(9) None
odds = set([1, 3, 5, 7, 9]) lows = set([0, 1, 2, 3, 4]) Example values: ten = set(range(10))
Alternative
Form
Method Purpose Example Result
Set Example
Have several files with observations of birds
Want to find out which species have been seen
Program:
lines = [
'canada goose', 'canada goose', 'long-tailed jaeger', 'canada goose',
'snow goose', 'canada goose', 'canada goose', 'northern fulmar'
]
seen = set()
for line in lines:
seen.add(line.strip())
for bird in seen:
print bird
northern fulmar
snow goose
long-tailed jaeger
canada goose
Note: for loops over the values in the set
Immutability
(^) This only works if a value's hash code never changes after it is inserted (^) If it does, the value will be in the wrong place Figure 9.2: Misplaced Values
Immutability
Python therefore only allows sets to contain immutable values
Booleans, numbers, strings, tuples…
…but not lists
values = set()
values.add('birds')
print values
values.add(('Canada', 'goose'))
print values
values.add(['snow', 'goose'])
print values
set([‘birds’])
set([(‘Canada’, ‘goose’), ‘birds’])
Traceback (most recent call last):
File "mutable_in_set.py", line 8, in?
values.add(['snow', 'goose'])
File "/usr/lib/python2.3/sets.py", line 521, in add
self._data[element] = True
TypeError: list objects are unhashable
This is one of the reasons tuples were invented
Allow you to store multi-part values like ("snow", "goose")
A Note on Language Design
Many languages allow mutable elements in
sets, and trust users not to modify them after
insertion
Which is a rich source of hard-to-find bugs
Could also have values keep track of which
sets they're in
“Move” them when their values change
Would make all programs slow for the benefit of a
few
Every software system contains tradeoffs like
this
Efficiency
So is using sets worthwhile?
Imagine storing species
names in a list instead of a
set
Each if name in seen check
requires N/2 comparisons on
average
So building up those N values
requires N(N+1)/
comparisons
Only requires N for a set
Difference is dramatic
Figure 9.3: List vs. Set Performance
Algorithmic Complexity
The relationship between problem size and running
time is called algorithmic complexity
Usually described in terms of upper bounds
If f(x) < kg(x) for large x and some constant k, then f(x) is
O(g(x))
For example:
Something that takes the same time, regardless of data size,
is O(1)
If the time grows as the logarithm of the data size, it is
O(log N)
If the time is proportional to the number of values, it is O(N)
Storing species names in a list is O(N2)
(^) Because if you throw away the constant 4, the difference
between N(N+1)/4 = (N2 + N)/4 and N2 becomes insignificant
as N grows large
Motivating Dictionaries
Suppose you want to count how
often each species of bird is seen
(^) Can't store (name, count) in set… (^) …because then you couldn't look up a species' count unless you already knew what it was
Could fall back on lists of pairs…
Better solution: store extra data with
each element of a set
A dictionary associates one value with
each of its keys
(^) An unordered mutable collection (^) Also called maps, hashes, and associative arrays (^) Often visualized as two-column table Figure 9.6: Dictionaries as Tables
Updating Dictionaries
Assigning to a dictionary key:
Creates a new entry if the key is not already in
dictionary
Overwrites the previous value if the key is already
present
birthday = {} birthday['Darwin'] = 1809 birthday['Newton'] = 1942 # oops birthday['Newton'] = 1642 print birthday {'Darwin': 1809, 'Newton': 1642}
Updating Dictionaries
Remove an entry using del d[k]
(^) Can only remove entries that are actually present birthday = { 'Newton' : 1642, 'Darwin' : 1809, 'Turing' : 1912 } print 'Before deleting Turing:', birthday del birthday['Turing'] print 'After deleting Turing:', birthday del birthday['Faraday'] print 'After deleting Faraday:', birthday Before deleting Turing: {'Turing': 1912, 'Newton': 1642, 'Darwin': 1809} After deleting Turing: {'Newton': 1642, 'Darwin': 1809} Traceback (most recent call last): File "dict_del.py", line 10, in? del birthday['Faraday'] KeyError: 'Faraday'
Membership and Loops
for k in d loops over the dictionary's keys (rather than its
values)
(^) Different from lists, where for loops over the values, rather than indices birthday = { 'Newton' : 1642, 'Darwin' : 1809, 'Turing' : 1912 } for name in birthday: print name, birthday[name] Turing 1912 Newton 1642 Darwin 1809
Dictionary Methods
Yes, dictionaries are objects too…
See the example below.
Copy keys and values from one dictionary into another.
updat e birthday.values() [1912, 1642, 1809]
Return the dictionary's values as a list. Entries may or may not be
unique.
value s [('Turing', 1912), ('Newton', 1642), ('Darwin', 1809)]
items Return a list of (key, value) pairs. birthday.items()
['Turing', 'Newton', 'Darwin'] birthday.keys()
Return the dictionary's keys as a list. Entries are guaranteed to be
unique.
keys Returns d['x'] if "x" is in d, or 99 if it is not.
Return the value associated with a key, or a default value if the key is d.get('x', 99)
not present.
get Returns None, but d is now empty.
clear Empty the dictionary. d.clear()
Purpose Example Result
Met
hod