MIME-Version: 1.0 Content-Location: file:///C:/F48430D9/Week9.htm Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset="us-ascii"
Week =
9
Lists and Dictionaries
Indiana University
Computer Science A202 /
A598
and Informatics I211
This
week’s success strategy
<=
![if !supportLists]>n Don't
procrastinate
<=
![if !supportLists]>q <=
/span>do reading for the week before lab (ideally before
lectures)
<=
![if !supportLists]>q <=
/span>do exercises in the text immediately after, or at
least shortly after, reading the text
<=
![if !supportLists]>q <=
/span>don't leave lab without understanding the assignme=
nt
<=
![if !supportLists]>q <=
/span>do the most difficult part of the assignment before
Tuesday
This =
week
<=
![if !supportLists]>n A
few more list operations
<=
![if !supportLists]>n Sorting
with comparitors
<=
![if !supportLists]>n Dictionaries
<=
![if !supportLists]>n Standard
input and output
Optio=
nal
and keyword argument exercise
<=
![if !supportLists]>n =
span>Exercise: define a function printArgs that
takes any number of arguments and prints the value of each on a separate li=
ne
<=
![if !supportLists]>n =
span>Answer:
def printArgs(*args):
for arg in
args:
print arg
<=
![if !supportLists]>n =
span>Exercise: define a function
>>> inGradeRange(100=
)
True
>>> inGradeRange(101=
)
False
>>> inGradeRange(101,
max=3D110)
True
>>> inGradeRange(10,
min=3D12)
False
<=
![if !supportLists]>n =
span>Answer:
def inGradeRange(grade, min=
=3D0,
max=3D100):
return min <=3D gra=
de <=3D
max
Some =
list
methods
<=
![if !supportLists]>n
.append(=
b>x)
<=
![if !supportLists]>q =
span>add x to the end of the list and return None
<=
![if !supportLists]>n
.reverse()
<=
![if !supportLists]>q =
span>reverse the list and return None
<=
![if !supportLists]>n
.index(x)
<=
![if !supportLists]>q =
span>return the index of the first occurrence of x in the list
<=
![if !supportLists]>n
.insert(=
b>i, x)
<=
![if !supportLists]>q
insert x into the
list at index i and return None
<=
![if !supportLists]>n
.remove(=
b>x)
<=
![if !supportLists]>q
delete the first occurr=
ence
of x in the list and return None
<=
![if !supportLists]>n &nb=
sp; .pop(i)
<=
![if !supportLists]>q =
span>deletes the ith element of the list and returns its value
<=
![if !supportLists]>n &nb=
sp; .count(x)
<=
![if !supportLists]>q =
span>returns the number of occurrences of x in the list
<=
![if !supportLists]>n
.sort(=
[comparitor])
<=
![if !supportLists]>q
sort the list in ascend=
ing
order according to comparitor (default cmp) and return=
None
Sorti=
ng
with comparitors
<=
![if !supportLists]>n =
span>A comparitor is a function that retu=
rns
-1, 0, or 1, if its first argument is less than, equal to, or greater than =
its
second argument, respectively
<=
![if !supportLists]>n =
span>The built-in function cmp is a comparitor
reflecting the usual < order relation
<=
![if !supportLists]>n =
span>Exercise: define a comparitor reverseCmp th=
at
sorts in reverse order
>>> lst =3D [5, 3, 6]
>>> lst.sort(cmp)
>>> lst
[3, 5, 6]
>>> lst.sort(reverseCmp)
>>> lst
[6, 5, 3]
<=
![if !supportLists]>n =
span>Answer
def reverseCmp(x, y):
return cm=
p(y,
x)
Exerc=
ise:
sequence position comparitor
<=
![if !supportLists]>n Write
a comparitor to sort a list of sequences on their second elements (rather t=
han
primarily on their first)
>>> lst =3D [('Sue', 23), ('Sam', 58), ('Tim', 18)]
>>> lst.sort()
>>> lst
[('Sam', 58), ('Sue', 23), ('Tim', 18)]
>>> lst.sort(cmp2nd)
>>> lst
[('Tim', 18), ('Sue', 23), ('Sam', 58)]
<=
![if !supportLists]>n Answer
def cmp2nd(seq1, seq2):
cmp(seq1[=
1],
seq2[1])
Compa=
ritor-valued
function
<=
![if !supportLists]>n =
span>A function that returns another function can be us=
ed
to generate comparitors that compare sequences based on the values of eleme=
nts
in any given position
>>> def cmpNth(n): # n is zero based
def returnedCmp(=
seq1,
seq2):
return cmp(seq1[n], seq2[n])
return returnedC=
mp
>>> lst.sort(cmpNth(0))
>>> lst
[('Sam', 58), ('Sue', 23), ('Tim', 18)]
>>> lst.sort(cmpNth(1))
>>> lst
[('Tim', 18), ('Sue', 23), ('Sam', 58)]
<=
![if !supportLists]>n =
span>Functions are first-class values in Python
<=
![if !supportLists]>q <=
/span>they can be passed to and returned from functions and stored in data
structures
Handy
uses for sequence operators
<=
![if !supportLists]>n&nb=
sp;
[x]
* n
<=
![if !supportLists]>q <=
/span>creates a sequence of n occurrences of x=
<=
![if !supportLists]>q <=
/span>useful to create lists that will have values assig=
ned
later
<=
![if !supportLists]>n &nb=
sp; if all elements are assigned later, then x can be anything
<=
![if !supportLists]>n seq
[:]
<=
![if !supportLists]>q <=
/span>copies seq by extracting a substring
that contains all elements
<=
![if !supportLists]>n&nb=
sp;
seq [::-1]
<=
![if !supportLists]>q <=
/span>returns a copy of seq that is revers=
ed
<=
![if !supportLists]>n&nb=
sp;
Adding x to the end of lst
<=
![if !supportLists]>q
lst=
.append(x) modifies lst
<=
![if !supportLists]>q <=
/span>lst + =
[x] returns a new list
<=
![if !supportLists]>q <=
/span>lst + x raises
and exception, unless x is a list
<=
![if !supportLists]>n &nb=
sp; a common error
Dicti=
onaries
<=
![if !supportLists]>n In
computer programs, as in life, it is often necessary to associate names (or
other 'keys') with values
<=
![if !supportLists]>n In
Python the primitive dictionary data type serves this purpose
<=
![if !supportLists]>n In
other languages such things may also be called maps, association
lists, hashes, and related names
<=
![if !supportLists]>n The
order of elements in a dictionary is not significant and is unpredictable
Dicti=
onary
syntax
<=
![if !supportLists]>n&nb=
sp;
Dictionary literal expression syntax:
=
{
<key> : <value> , … , <key> : <val=
ue>
}
<=
![if !supportLists]>q <=
/span>where each <key> and <value> may be any
expression, provided no two <key> expressions have the same value
<=
![if !supportLists]>q <=
/span>{} is an
empty dictionary (and is a false value)
<=
![if !supportLists]>n Dictionary
values may be referenced, assigned, and deleted with the same syntax used f=
or
lists, except now key values replace indexes
<=
![if !supportLists]>q <=
/span>assignment of a value to a key not already in the
dictionary adds the key/value association to the dictionary
<=
![if !supportLists]>n Given
a dictionary as the iteration object, a for loop will iterate over i=
ts
keys.
Dicti=
onary
example
>>> dict =3D {'Jan': 31, 'Feb': 28, 'Mar': 31}
>>> dict['Apr'] =3D30
>>> dict
{'Jan': 31, 'Apr': 30, 'Mar': 31, 'Feb': 28}
>>> dict['Feb'] =3D 29
>>> dict
{'Jan': 31, 'Apr': 30, 'Mar': 31, 'Feb': 29}
>>> for m in dict:
print '%s =
has %d
days' % (m, dict[m])
Jan has 31 days
Apr has 30 days
Mar has 31 days
Feb has 29 days
>>> del dict['Jan']
>>> dict
{'Apr': 30, 'Mar': 31, 'Feb': 29}
Dicti=
onary
methods
<=
![if !supportLists]>n
.has_key(<=
/b>key)
<=
![if !supportLists]>q <=
/span>returns a boolean indicating if the dictionary has an association for
the key
<=
![if !supportLists]>q
same as: key =
in
dict
<=
![if !supportLists]>n
.keys()
<=
![if !supportLists]>q <=
/span>returns a list of the dictionary's keys
<=
![if !supportLists]>n =
span>.values()
<=
![if !supportLists]>q <=
/span>returns a list of the dictionary's values (may include duplicate val=
ues)
<=
![if !supportLists]>n
.items()
<=
![if !supportLists]>q <=
/span>returns a list of (key, value) pairs representing the
dictionary's associations
<=
![if !supportLists]>n
.get(<=
i>key, default)
<=
![if !supportLists]>q <=
/span>returns the value associated with key, or default <=
/i>if
the dictionary has no association for the key
<=
![if !supportLists]>n
.clear()
<=
![if !supportLists]>q <=
/span>deletes all associations in the dictionary and returns None
makeDictionary function
<=
![if !supportLists]>n =
span>Define the function makeDictionary, which t=
akes
a sequence of (key, value) pairs and returns the corresponding dictionary
>>> items =3D dict.items()
>>> items
[('Apr', 30), ('Mar', 31), ('Feb', 29)]
>>> makeDictionary(items)
{'Apr': 30, 'Mar': 31, 'Feb': 29}
<=
![if !supportLists]>n =
span>Answer
def makeDictionary(items):
'''Return=
a
dictionary with those associations
indicated=
by
(key, value) pairs in items list.'''
dict =3D =
{}
for key, =
value
in items:
if
key in dict:
=
raise Exception(key + ' already in dictionary')
dict[key] =3D value
return di=
ct
invertDictionary function
<=
![if !supportLists]>n Write
a function that takes a dictionary and returns a dictionary obtained by
reversing the key/value roles in its associations
>>> dict
{'Apr': 30, 'Mar': 31, 'Feb': 29}
>>> invertDictionary(dict)
{29: 'Feb', 30: 'Apr', 31: 'Mar'}
<=
![if !supportLists]>n Solution
def invertDictionary(dict):
invertedD=
ict =3D
{}
for key in
dict:
if
dict[key] in invertedDict:
=
raise Exception('dictionary is not 1-to-1')
invertedDict[ dict[key] ] =3D key
return
invertedDict
Stand=
ard
input and standard output
<=
![if !supportLists]>n Every
application started by an operating system shell (or the IDLE) associated
standard input and standard output streams (of characters)
<=
![if !supportLists]>q <=
/span>By default these are associated with keyboard input
and console (command or IDLE shell window) output
<=
![if !supportLists]>q <=
/span>They may be redirected to files using the Windows =
or
Unix command line operators "<" and ">"=
,
respectively
<=
![if !supportLists]>n These
are available in Python as file-like objects stored in sys.stdin and=
sys.stdout,
respectively
<=
![if !supportLists]>q
input =
and raw_input read from sys.stdin
<=
![if !supportLists]>n
readline() may also be used to read from sys.stdin, but not readlines=
()
or read()
<=
![if !supportLists]>q
print<=
span
style=3D'font-size:10.0pt;font-family:Arial;mso-bidi-font-family:Arial;
mso-bidi-language:#AC45'> writes to sys.stdout
<=
![if !supportLists]>n &nb=
sp; sys.stdout.write(…) may =
also
be used
<=
![if !supportLists]>q
attempting to close
stdin or stdout may result in an error
Stand=
ard
input and output redirection examples
<=
![if !supportLists]>n Run
application app.py with argument arg and output to file ou=
t.txt
instead of the console
python app.py arg > out.txt
<=
![if !supportLists]>n Run
application as above, but also with input from the file in.txt inste=
ad
of the keyboard
python app.py arg > out.txt < in.txt
<=
![if !supportLists]>n =
Standard error (sys.stderr) is the same as
standard output by default, but may be redirected differently
<=
![if !supportLists]>q used
for error messages
<=
![if !supportLists]>q&nb=
sp; not
used in this course
def makeDictionary(items):
'''Return a dictionary with those associations indicated by (key, value)
pairs in items list.'''
dict =3D {}
for key, value in items:
if key in dict:
raise Exception(key + ' is already in dictionary')
dict[key] =3D value
return dict
def invertDictionary(dict):
'Return a dictonary derived by reversing the key/value roles in dict.'
invertedDict =3D {}
for key in dict:
if dict[key] in invertedDict:
raise Exception('dictionary is not one-to-one')
invertedDict[dict[key]] =3D key
return invertedDict