Computer Science. Chapter 11. Data Collections. Python Programming, 1/e. 2.
Objectives. ▫ To understand the use of lists (arrays) to represent a collection of ...
! " "
#
# $ # #
' ! &
"
% &
# ' #
#
&
,) ! "
-
'
' #
#
)
&
.
& "
# #
#
*
) #
&
/
' 0
(
23
!'
' '
4
+
" * # '
# average4.py # A program to average a set of numbers # Illustrates sentinel loop using empty string as sentinel def main(): sum = 0.0 count = 0 xStr = raw_input("Enter a number ( to quit) >> ") while xStr != "": x = eval(xStr) sum = sum + x count = count + 1 xStr = raw_input("Enter a number ( to quit) >> ") print "\nThe average of the numbers is", sum / count
' # 3 0 6 & ' '
0# 0 ) !
&
main() 1
Python Programming, 1/e
5
1
"
! * 8 9 + 5 ; ( ' ! ' !
: 5 5 '
!
"
& #
! !
!
& #
& & !
"
#
# ' &
!
)
&
0 ' )
&
7
"
!
( x − xi )
s=
n −1
x
# ! &
!
> '
& + 5 ;
(&
# *
# =
" "
#
5&4 #
!
( 6.8 − 2 ) + ( 6.8 − 4 ) + ( 6.8 − 6 ) + ( 6.8 − 9 ) + ( 6.8 − 13) 2
#
2
2
2
2
= 149.6
149.6 s= = 37.4 = 6.11 5 −1 ;
?
2 . ! $'
# .
3
!
'
@ .
'
Python Programming, 1/e
3 '
% . !
'
*
&
& #!
3 0 ' &
'
A
'
# #!
&
2
2
2
:
B
* #
* ?
(
C
#!
#
&
s& .
! *
8
*
* ' #
0
sum = 0 for i in range(n): sum = sum + s[i]
#
& D 9
!
!
*
!
&
n −1 i =0
*
0 &
si (
2
+
2 * * $ & & s%
#
'
&"
# ! $ & & s[i]%&
) #)
'
9 !
' # '
0
& & #
* &
& & 1
2
2 ,) # ' 3! & " # '
E *F K E *F E *F JE 8 ) F I E *FG H $E *F% 2 E *FGH # E! F E *F E ) F E *F -
)
0 # ! *
>>> lst = [1,2,3,4] >>> 3 in lst True
$D
&
% 7
Python Programming, 1/e
5
4
3
2
2
" '
)
#
#
0
&"
sum = 0 for x in s: sum = sum + x
1?
L 0 >>> >>> 4 >>> >>> [1, >>> >>> [1,
9 zeroes = [0] * 50
lst = [1,2,3,4] lst[3] lst[3] = "Hello“ lst 2, 3, 'Hello'] lst[2] = 7 lst 2, 7, 'Hello']
;
?
2
2
2
-
# &
nums = [] x = input('Enter a number: ') while x >= 0: nums.append(x) x = input('Enter a number: ')
+7
Python Programming, 1/e
# 0
' 0' sort '
& . ' 0# ' & " / ' 0 ' -1 0 1&
cmp("a","b")
'
+5
'
' sort
cmp8
'
+4
8
2
#
2
.
cmp #
8
data.sort(cmpGPA) N ' 3 # cmpGPA&
&
def cmpGPA(s1, s2): return cmp(s1.gpa(), s2.gpa()
.
'
" cmpGPA cmpGPA
' # $cmpGPA% data.sort(cmpGPA)
#
&
'
()3
#
3 ' ' '
& +;
1?
' 2 O O
#
2
&
# #
&
0
$% Q " #
# # # B # #&
$# $# BG H # & $
%$#' # B # # &' #&
$ $#
B # Q % B & $ # B # ' Q "
% PP %
0
# P 'P %
$
% $ &
# #
/ $
/
%%
#UU
%
'U
%$&
dieView 0
$%%
/ Q $Q ,
#
$#
%
/ % 'U $Q , Q % $ #
UUBB P UU
#
& ' ! 0 pip2 pip3 C
# % '
#
!
Q#
UUP
%$$Q R S R# S R# S QR $ & N $% & < $% & T $%%%
%$# 0# ! # # 0#
pip1
1
1
'
'
2
2
.
#' A
' #
! 0
'
& pips = [] pips.append(self.__makePip(cx-offset,cy-offset) pips.append(self.__makePip(cx-offset,cy) … self.pips = pips
self.pip1 = self.__makePip(cx, cy)
__makePip DieView
# !
&
1(
Python Programming, 1/e
1+
9
'
'
2
2 !
#'
0
&
#
self.pips = [self.__makePip(cx-offset,cy-offset), self.__makePip(cx-offset,cy), … self.__makePip(cx+offset,cy+offset) ]
"
! #
2
for pip in self.pips: pip.setFill(self.background)
#
VH3& 0 &
0 0
0 ' '
&
"
!
0
#
!
'@ 11
15
'
'
2
2
.
0 &
< 0
3
!
'
0 for i in [0,3,6]: self.pips[i].setFill(self.foreground)
self.pip1.setFill(self.foreground) self.pip4.setFill(self.foreground) self.pip7.setFill(self.foreground)
.
0
! 0
# #'
! @
self.pips[0].setFill(self.foreground) self.pips[3].setFill(self.foreground) self.pips[6].setFill(self.foreground)
Loop through pips and turn them all off Determine the list of pip indexes to turn on Loop through the list of indexes - turn on those pips 17
14
'
'
2
2
for pip in self.pips: self.pip.setFill(self.background) if value == 1: on = [3] elif value == 2: on = [0,6] elif value == 3: on = [0,3,6] elif value == 4: on = [0,2,4,6] elif value == 5: on = [0,2,3,4,6] else: on = [0,1,2,3,4,5,6] for i in on: self.pips[i].setFill(self.foreground)
. ! @ " # value& . 0 ! & . ' # # ) & : ) [0,3,6]
( ' !
1;
Python Programming, 1/e
8
#(& 5?
10
'
'
2
& p
0
'
! #
0 & & #key text #
# '
#
0
# #
"
for
) &
#
self.display.setText(text+key) 77
Python Programming, 1/e
74
13
D "
0
D try:
0
result = eval(text) except: result = 'ERROR‘ self.display.setText(str(result))
self.display.setText(“”)
"
0
0
# #
,) 8 !
self.display.setText(text[:-1])
"
* !
0
)
#
)
3
) '
3 ERROR
&
& #
&
7;
N 8
4?
*
D
!
8
#
" #
&
N
' *
!
# '
0
)
! !
' &
'
& '
! &
4
4
D " . # $ 3
# 0 ' ! $ %
D '
0 8! '
0# '
&
' 0
'
0
&
0
&
%& 0 8!
!
&
& 4(
Python Programming, 1/e
4+
14
D
D "
#
0 8! &
' )
0
>>> passwd = {"guido":"superprogrammer", "turing":"genius", "bill":"monopoly"}
W
0
!
!
'
V3 &
&
>>> passwd["guido"] 'superprogrammer' >>> passwd["bill"] 'monopoly'
[] '
! 0 &
41
45
D
D &" !
'
0
'
&
>>> passwd["bill"] = "bluescreen“ >>> passwd {'turing': 'genius', 'bill': 'bluescreen', 'guido': 'superprogrammer'}
0 0 # ' *
0 ! 0
' &
# #
#
@
3 ' &
-
A 47
44
D ! # ! W !
0
8
&
&
) #
%
$ '
& 8
#
>>> passwd['newuser'] = "ImANewbie“ >>> passwd {'turing': 'genius', 'bill': 'bluescreen', 'newuser': 'ImANewbie', 'guido': 'superprogrammer'}
&
4;
Python Programming, 1/e
;?
15
passwd = {} for line in open('passwords', 'r'): user, pass = string.split(line) passwd[user] = pass
' ' 0 8!
& ' # passwords # # '
' ' &
;
-
-
.has_key()
I
in
# # 0 # has_key
' &
.keys()
I
#
0 &
.values()
I
#
!
.items()
I
# (key, value) 0 8! &
.get(, )
&
key default
# '
del []
#
.clear()
!
M
&
&
;
>>> passwd.keys() ['turing', 'bill', 'newuser', 'guido'] >>> passwd.values() ['genius', 'bluescreen', 'ImANewbie', 'superprogrammer'] >>> passwd.items() [('turing', 'genius'), ('bill', 'bluescreen'), ('newuser', 'ImANewbie'), ('guido', 'superprogrammer')] >>> passwd.has_key('bill') True >>> 'fred' in passwd False >>> passwd.get('bill', 'unknown') 'bluescreen' >>> passwd.get('john', 'unknown') 'unknown' >>> passwd.clear() >>> passwd {}
;(
,) .
,) .
: *
N'
'
;+
!
: *
'
! 9
'
)
' &
"
. ' '
' )
! '
'
# #
#
$ 0
' & '3
.
%&
# ;1
Python Programming, 1/e
'
&
# # !
8 ' #
# @ ;5
16
,) .
,) .
: *
.
'
0
: *
" 3 ' counts& ) 0 KeyError&
' !
' & 23 counts& " # ' w counts[w] = counts[w] + 1 '
" # 3
'
8 8
if w is already in counts: add one to the count for w else: set count for w to 1
;7
,) .
;4
,) .
: *
" '
: *
# counts[w] = counts.get(w,0) + 1
' '
#w
#&
get ? # w
if counts.has_key(w): counts[w] = counts[w] + 1 else: counts[w] = 1
&
;;
,) .
,) .
: *
" #
0 *
. !
'
=
>
=
@ >
??
= '
> =
) #' )' $ ' % ! $ >%&
: *
fname = raw_input("File to analyze: ") # read file as one long string text = open(fname, 'r').read()
&
# convert all letters to lower case text = string.lower(text)
0
# replace each punctuation character with a space for ch in '!"#$%&()*+,-./:;?@[\\]^_{|}~': text = string.replace(text, ch, ' ') # split string at whitespace to form a list of words words = string.split(text) # Now we can easily loop through the words to build # the counts dictionary ?
Python Programming, 1/e
?
17
,) .
,) .
: *
: *
.
# get list of words that appear in document uniqueWords = counts.keys()
counts = {} for w in words: counts[w] = counts.get(w, 0) + 1
# put list of words in alphabetical order uniqueWords.sort()
. . c2: return -1 elif c1 == c2: return cmp(w1, w2) else: return 1
# ' 8 8 ? &
def compareItems((w1, c1), (w2, c2)): if c1 > c2: return -1 elif c1 == c2: return cmp(w1, w2) else: return 1
" # ' 8! #
0 &
' #
#
# '
?7
Python Programming, 1/e
?5
-1& ?4
18
.
: *
.
def compareItems((w1, c1), (w2, c2)): if c1 > c2: return -1 elif c1 == c2: return cmp(w1, w2) else: return 1
def compareItems((w1, c1), (w2, c2)): if c1 > c2: return -1 elif c1 == c2: return cmp(w1, w2) else: return 1
# '
' ' ! '
*
'
2
0 &"
3 '
: *
'
# 1&
"
&
items.sort(compareItems)
?;
.
: * &
import string
#8
.
def compareItems((w1,c1), (w2,c2)): if c1 > c2: return -1 elif c1 == c2: return cmp(w1, w2) else: return 1
# : N =
#
'
? 8
'3 >
: *
# wordfreq.py # Program to analyze the frequency of words in a text file. # Illustrates Python dictionaries
for i in range(n): print "%-10s%5d" % items[i]
N
?
.
" '
'
' ! GH
#
1 # ' !
def main(): print "This program analyzes word frequency in a file" print "and prints a report on the n most frequent words.\n"
&
: *
# get the sequence of words from the file fname = raw_input("File to analyze: ") text = open(fname,'r').read() text = string.lower(text) for ch in '!"#$%&\'()*+,-./:;?@[\\]^_`{|}~': text = string.replace(text, ch, ' ') words = string.split(text) # construct a dictionary of word counts counts = {} for w in words: counts[w] = counts.get(w,0) + 1 # output analysis of n most frequent words. n = input("Output analysis of how many words? ") items = counts.items() items.sort(compareItems) for i in range(n): print "%-10s%5d" % items[i] (
Python Programming, 1/e
19