Professional Documents
Culture Documents
Az in Pas Python - Ebook PDF
Az in Pas Python - Ebook PDF
Az in Pas Python - Ebook PDF
/ . :.1382
330.
.1 ) (
005/133 QA76/73
33
2303798 :2358465 :
80 79 76 74 81
77
:
:
:
1000 :
: 1382
:
:
:
:
:
964-7999-30-5 :
.
from.now.on.python@gmail.com .
.
.
.
.
.
.
.
.
.
.
.
.
.
C
.
C
. ++C
C++
.
1990
) (CWI Guido van Rossum . Guido
Monty Python's Flying Circus
.
.
Python .
Scripting Language
Amoeba Guido
.
.
) (GUIs
C++ .
OS/2 Unix Windows ... .
C C++
.
.
. - .
.
C .
.
.
.
.
.
How To Think Like a Computer Scientist
. 20
.
.
CD ) (
.
1 ........................................................................................................................
-1-1 2 ................................................................................................................................................
-2-1 4 ..................................................................................................................................................................
-3-1 5 .......................................................................................................................................................
-1-3-1 5 ............................................................................................................................................................
-2-3-1 6 .....................................................................................................................................................
-3-3-1 6 ..........................................................................................................................................................
-4-3-1 6 .................................................................................................................................................
-4-1 7 ...............................................................................................................................................
-5-1 9 ........................................................................................................................................................................
-6-19 ................................................................................................................................................................................
13 .....................................................................................................
-1-2 14 .....................................................................................................................................................
-2-2 15 ............................................................................................................................................................................
-3-2 16 ................................................................................................................................
-4-2 17 .........................................................................................................................................................................
-5-2 18 ................................................................................................................................................................
-6-2 19 ......................................................................................................................................................
-7-2 20 ..............................................................................................................................................................
-8-2 21 ...............................................................................................................................................
-9-2 22 ..............................................................................................................................................................................
-10-2 22 .....................................................................................................................................................................
-11-2 23 .........................................................................................................................................................................
27 ..........................................................................................................................................
-1-3 28 ..................................................................................................................................................................
-2-3 29 ..............................................................................................................................................................
-3-3 30 ............................................................................................................................................................
-4-3 30 ....................................................................................................................................................................
-5-332 ............................................................................................................................................................................
-6-3 33 ..............................................................................................................................................................................
-7-3 33 ...............................................................................................................................................
-8-3 36 .............................................................................................................................................
-9-3 36 ..........................................................................................................................................................................
-10-3 37 ................................................................................................................................................
-11-3 39 ..........................................................................................................................
-12-3 40 .........................................................................................................................................................
-13-3 41 .............................................................................................................................................................
-14-3 42 .........................................................................................................................................................................
45 ..................................................................................................................
-1-4 46 ............................................................................................................................................................
-2-4 47 ....................................................................................................................................................................
-3-4 47 .........................................................................................................................................................
-4-4 48 ...................................................................................................................................................
-5-4 49 ............................................................................................................................................
-6-4 50 .........................................................................................................................................
-7-4 51 ...............................................................................................................................................
-8-4 52 ....................................................................................................................................................... return
-9-4 52 ................................................................................................................................................................
-10-4 54 ....................................................................................................................
-11-4 55 ...........................................................................................................................................................
-12-4 55 ......................................................................................................................................................
-13-4 57 .........................................................................................................................................................................
59...........................................................................................................................
-1-5 60 ..............................................................................................................................................................
-2-5 61 ...................................................................................................................................................................
-3-5 64 ..............................................................................................................................................................................
-4-5 65 ........................................................................................................................................................................
-5-5 66 ..........................................................................................................................................................
-6-5 69 ..........................................................................................................................................................
-7-5 69 ......................................................................................................................................................................
-8-5 70 ........................................................................................................................................................
-9-5 72 ............................................................................................................................................................................
75 ..........................................................................................................................................
-1-6 76 .............................................................................................................................................................
-2-6 77 ........................................................................................................................................................... while
-3-6 79 ...........................................................................................................................................................................
-4-6 82 .............................................................................................................................................................
-5-6 82 .......................................................................................................................................................
-6-6 84 ......................................................................................................................................................
-7-6 84 ............................................................................................................................................................
-8-6 85 .............................................................................................................................................................
-9-687 ..................................................................................................................................................................................
-10-6 87 ..........................................................................................................................................................................
91........................................................................................................................................
-1-7 92 ..........................................................................................................................................................
-2-7 93 ......................................................................................................................................................................
-3-7 93 ................................................................................................................................................. for
-4-7 95 ...............................................................................................................................................................
-5-7 96 ..............................................................................................................................................................
-6-7 96 ....................................................................................................................................................
-7-7 97 ........................................................................................................................................................... find
-8-7 98 ........................................................................................................................................................
-9-7 98 ........................................................................................................................................................ string
-10-7 99 ..................................................................................................................................................
-11-7 101 ......................................................................................................................................................................
103 ....................................................................................................................................
-1-8 104 ...............................................................................................................................................................
-2-8 105 .......................................................................................................................................................
-3-8 107 .................................................................................................................................................................
-4-8 107 .............................................................................................................................................................
-5-8 108 .........................................................................................................................................for
-6-8 109 ........................................................................................................................................................
-7-8 109 ..........................................................................................................................................................
-8-8 110 .................................................................................................................................................
-9-8 111 .................................................................................................................................................................
-10-8 111 ...........................................................................................................................................................
-11-8112 ...................................................................................................................................................................
-12-8 113 ..........................................................................................................................................................
-13-8 114 .......................................................................................................................................
-14-8 115 .....................................................................................................................................................
-15-8 116 ..................................................................................................................................................................
-16-8 116 ...................................................................................................................................................
-17-8 117 ......................................................................................................................................................................
119 ................................................................................................................................
-1-9 120 .........................................................................................................................................
-2-9 121 ..........................................................................................................................................
-3-9 122 ....................................................................................................................
-4-9 123 ..............................................................................................................................................................
-5-9 123 ............................................................................................................................................
-6-9 124 .........................................................................................................................................................................
-7-9 125 ..............................................................................................................................................................
-8-9 127 ................................................................................................................................................
-9-9 128 .........................................................................................................................................................................
131 .............................................................................................................................
-1-10 133 .................................................................................................................................
-2-10 134 ..................................................................................................................................................
-3-10 135 ........................................................................................................................................
-4-10 135 ...............................................................................................................................................
-5-10 137 .................................................................................................................................................................
-6-10 139 ..................................................................................................................................................
-7-10 140 .........................................................................................................................................................
-8-10 140 ......................................................................................................................................................................
143..................................................................................................................
-1-11 146 .........................................................................................................................................................
-2-11 148 .........................................................................................................................................................
-3-11 150 .............................................................................................................................................................
150 ................................................................................................................................................................ Pickling -4-11
-5-11 152 ......................................................................................................................................................................
-6-11 154 .......................................................................................................................................................................
157...........................................................................................................................
-1-12 - 158 .....................................................................................................................................
-2-12 159 .................................................................................................................................................................
-3-12 160 ......................................................................................................................................
-4-12 161 .........................................................................................................................................................
-5-12 162 ....................................................................................................................................................................
-6-12 163 ..........................................................................................................................
-7-12 163 ....................................................................................................................................................
-8-12 164 ................................................................................................................................................................
-9-12 166.......................................................................................................................................................................
169 ........................................................................................................................
-1-13 170 ...........................................................................................................................................................................
-2-13 171 ...............................................................................................................................................................
-3-13 172 ...........................................................................................................................................................
-4-13 173 ......................................................................................................................................................
-5-13 174 .............................................................................................
-6-13 175 .........................................................................................................................................................................
-7-13 176 .................................................................................................................................................................
-8-13 177 ......................................................................................................................................................................
179 .......................................................................................................................
-1-14 180 ................................................................................................................................................
181 ................................................................................................................................................... printTime -2-14
-3-14 182 ................................................................................................................................................................
-4-14 183 .................................................................................................................................................
-5-14 184 .............................................................................................................................................
-6-14 185 ................................................................................................................................................
-7-14 186 ........................................................................................................................................... Point
-8-14 187 ..............................................................................................................................................
-9-14 189 ................................................................................................................................................................
-10-14191 ....................................................................................................................................................................
193...................................................................................................................
-1-15 194 ........................................................................................................................................................................
-2-15 194 ........................................................................................................................................................... Card
-3-15 __196 .......................................................................................................... __str
-4-15 197 ........................................................................................................................................................
-5-15 198 ..........................................................................................................................................................
-6-15 199 ...............................................................................................................................................
-7-15 201 ............................................................................................................................................
-8-15 202 ..........................................................................................................................................
-9-15 203 ......................................................................................................................................................................
205 ........................................................................................................................................
-1-16 206 ..........................................................................................................................................................................
-2-16 206 .......................................................................................................................................................
-3-16 208 ...........................................................................................................................................................
-4-16 209 .............................................................................................................................................
-5-16 210 .......................................................................................................................................... CardGame
-6-16 211 ................................................................................................................................ OldMaidHand
-7-16 212 ............................................................................................................................... OldMaidGame
-8-16 216 .......................................................................................................................................................................
219
219 ...................................................................................................................
-1-17 220 ........................................................................................................................................................
-2-17 220 ......................................................................................................................................................... Node
-3-17 222 ....................................................................................................................................
-4-17 223 ..................................................................................................................................................
-5-17 224 ................................................................................................................................................
-6-17 225 ...................................................................................................................................................
-7-17 226 ................................................................................................................................................
-8-17 227 ...................................................................................................................................
-9-17 228 ................................................................................................................................... LinkedList
-10-17 229 .................................................................................................................................................................
-11-17230 ....................................................................................................................................................................
233....................................................................................................................................
-1-18 234 ..................................................................................................................................................
-2-18 235 ...........................................................................................................................................................................
-3-18 235 .............................................................................................................
-4-18 236 ................................................................................................................
-5-18 237 ............................................................................................. postfix
-6-18238 ..........................................................................................................................................................................
-7-18 238 .................................................................................................................................. postfix
-8-18 239 ...........................................................................................................................................
-9-18 240 ......................................................................................................................................................................
243 ......................................................................................................................................
ADT -1-19 244 ................................................................................................................................................................
-2-19 244 .............................................................................................................................................................
-3-19 246 ...................................................................................................................................................
-4-19 246 ........................................................................................................................................
-5-19 248 ...............................................................................................................................................................
-6-19 250 .................................................................................................................................................. Golfer
-7-19 251 ......................................................................................................................................................................
253..................................................................................................................................
-1-20 255 ......................................................................................................................................................
-2-20 256 ....................................................................................................................................................
-3-20 256 ...................................................................................................................................................
-4-20 257 .......................................................................................................................................................
-5-20 259 ....................................................................................................................................
-6-20 263 .....................................................................................................................................................
-20-7 264 .........................................................................................................................................................
-8-20 266.......................................................................................................................................................................
269 ..................................................................................................................
-1-21 270 ......................................................................................................................................................................
-2-21 271 ...............................................................................................................................................
-3-21 274 .................................................................................................................................................
-4-21 274 .......................................................................................................................................................
275 .............................................................................................................................................................. lambda -5-21
-6-21 277 ....................................................................................................................................................
-7-21 278 .............................................................................................................................................
-8-21 281 ..................................................................................................................................................................
-9-21 285 .....................................................................................................................................
-10-21 286 ....................................................................................................................................................
-11-21 else 287 ...................................................................................................................................
-12-21289 ....................................................................................................................................................................
291 ..............................................................................................
-1- 292 ........................................................................................................................................ IDLE
-1-1- 292 ........................................................................................................................... IDLE
-2-1- 293 ............................................................................................................... Python Shell
-3-1- 294 ...........................................................................................................................................................
-4-1- 294 .......................................................................................................................................................
-5-1- 295 ........................................................................................................................................................
-6-1- 295 .............................................................................................................................................
-7-1- 296 .........................................................................................................................
-8-1- 297 .................................................................................................................................
-1-8-1- 298 ..........................................................................................................................................
-2-8-1- 299 ..................................................................................................................................
-3-8-1- 300 .............................................................................................................................................
-9-1- 300 ................................................................................... Find/Replace
-10-1- )301 ......................................................................................... (Path Browser
302 ........................................................................................................................................................ PythonWin -2-
-1-2- 302 ......................................................................................................................................................
-2-2- 303 .................................................................................................................................................
305 .............................................................................................................
-1- 306 ..........................................................................................................................................................
-2- 306 ....................................................................................................................................................................
-3- 307 .......................................................................................................................................................
-4- 310 .........................................................................................................................................................
-5- - 310 ........................................................................................................................................
-6- 311 ...................................................................................................................................................
313 ..........................................................................................................................
.
.
)
( .
.
.
.
.
.
.
.
.
-1-1
.
C .
.
.
.
.
:
.
. .
.
.
3 :
.
.
.
.
:
.
. :
. : .
:
.
. >>>
4
print 1+1
.py.
1
:
$ python latoya.py
2
.
.
.
.
.
-2-1
.
. . ..
:
: .
-1 .
.
5 :
:
.
: .
: .
: .
:
.
.
-3-1
.
Bug Debugging
.
:
-3 -2 -1
-1-3-1
.
.
. " "this is a book.
.
6
. - -
.
.
-2-3-1
.
.
.
.
-3-3-1
.
. .
.
.
-4-3-1
.
.
.
.
7 :
.
.
.
:
.
.
.
.
Intel 80386 .
: AAAA
BBBB . .
.
-4-1
. . . .
.
.
.
.
8
. 3+3=6
3+=6$ H2O .
2zZ .
. .
3+=6$ ) $ ( . 2zZ
zZ .
.
3+=6$ =
+ .
.
.
.
.
. .
.
)
( :
:
.
.
)( :
.
: .
.
.
:
.
9 :
) ( .
.
.
.
.
-5-1
"Hello,aWorld!"
! Hello, World .
:
"!print "Hello, World
. :
!Hello, World
)(
.
"! "Hello,aWorld . .
-6-1
) problem solving (
.
10
) high-level language (
.
) low-level language (
.
) portable (
.
) interpret(
.
) compile (
.
) source code (
.
) object code (
.
) executable (
.
) script(
) (.
) program(
.
11 :
) algorithm(
.
) bug(
.
) debugging(
.
) syntax (
.
) syntax error (
) ( .
) runtime error (
.
) exception(
.
) semantic error (
.
) semantics(
.
) natural language (
.
12
) formal language (
. .
) token (
.
) parse(
.
) print statement (
.
14
.
.
.
.
-1-2
"!"Hello,aWorld . ) 2 (1+1
.
2 .
"! "Hello,aworld . )
( . ) (
)"( )'( .
:
>>> print 4
4
str int . )
( float
.
)>>> type(3.2
>'<type 'float
15 :
)">>> type("17
>'<type 'str
)">>> type("3.2
>'<type 'str
.
') ',( .1,000,000
:
. 1,000,000
.
.
-2-2
.
.
:
. "? "What'saupaDoc
message . 17 n
3.14159 pi.
16
.
. 1-2 .
1-2
.
.
)>>> type(message
>'<type 'str
)>>> type(n
>'<type 'int
)>>> type(pi
>'<type 'float
-3-2
.
.
17 :
.
.
.
) ( Bruce . bruce .
) _ ( .
my_name . price_of_tea_in_china
:
76trombones more$ .
) ($ . class
class .
.
28 :
.
.
-4-2
.
: .
18
.
.
.
.
:
print 1
x = 2
print x
:
1
2
-5-2
.
.
>>> 1 + 1
2
>>> 17
17
>>> x
2
.
.
print .
.
:
17
3.2
"!"Hello, World
1 + 1
-6-2
.
.
:
- + /
. )*( )**(
.
.
. :
>>> minute = 59
>>> minute/60
0
20
minute 59 . 59 60 0.98333
. .
) (1 .
:
>>> minute*100/60
98
.
.
-7-2
.
.
PEMDAS .
:
. 2*(3-
) 1 4 ) (1+1)**(5-2 8 .
. (minute*100)/60
.
2**1+1 3
4 3*1**3 3 . 27
21 :
.
2*3-1 5 4
2/3-1 1 ) 1 . (2/3=0
minute*100/60 5900/60
98 .
59*1 59 .
-8-2
. ) message (:
+
. + .
. :
"fruit = "banana
"bakedGood = " nut bread
print fruit + bakedGood
-9-2
.
.
:
>>> print 17 + 3
20
.
. .
: .
:
. minute+1 = hour
-10-2
.
.
.
# :
23 :
.
:
#
.
.
.
-11-2
) value(
) (
.
) type(
. .
) (int ) (float
) .(str
) floating-point (
.
) variable(
.
24
) statement (
.
.
) assignment(
.
) state diagram (
.
) keyword (
while def if . . .
.
) expression(
.
) evaluate(
.
) operator(
.
) operand(
.
) integer division (
.
.
25 :
) rules of precedence (
.
) concatenate(
.
) composition(
.
) comment(
)
( .
28
.
.
.
.
.
.
-1-3
:
)">>> type("32
>'<type 'str
type .
.
. .
:
id .
:
)>>> id(3
134882108
>>> betty = 3
)>>> id(betty
134882108
29 :
id . id
id . id .
-2-3
. int
:
)">>> int("32
32
)">>> int("Hello
ValueError: invalid literal for int(): Hello
int
:
)>>> int(3.99999
3
)>>> int(-2.3
-2
float :
)>>> float(32
32.0
)">>> float("3.14159
3.14159
str :
)>>> str(32
''32
)>>> str(3.14149
''3.14149
1.0 1
.
. .
30
-3-3
.
. minute/60
59 !
minute
:
>>> minute = 59
>>> float(minute) / 60.0
0.983333333333
.
.
:
>>> minute = 59
>>> minute / 60.0
0.983333333333
-4-3
sin log
) sin(pi/2 ) log(1/x . )(
. pi/2 1.571 1/x x 10.0
0.1.
.
1.571 1 ) 0.1 (10 1.
31 :
)) log(1/sin(pi/2
.
.
math .
.
import :
>>> import math
. .
17 10 decibel .
log ) e ( .
angle sin .
) cot tan ( .
180 pi . 45
:
>>> degrees = 45
>>> angle = degrees * math.pi / 180
)>>> math.sin(angle
pi math .
2 2:
-5-3
. .
.
.
Enter ) (
.
.
. .py
.
.
.
from...import
. :
cos exp :
) (
* :
math )
)( ( .
33 :
-6-3
.
.
:
)>>> x = cos(angle + pi/2
pi 2 angle
cos.
:
))>>> x = exp(log(10.0
10 e e .
x .
-7-3
.
.
. .
.
.
:
. ) (LIST OF PARAMETERS
) ( .
34
.
2.
.
:
def newLine():
print
newLine .
) .
print (
:
First line.
Second line.
.
:
threeLines :
indent-2
35 :
def threeLines():
)(newLine
)(newLine
)(newLine
.
.
:
.1 .
.
.2 .
threeLines newLine .
.
:
.
) ( .
.
threeLines
.
-8-3
6-3 :
def newLine():
print
def threeLines():
)(newLine
)(newLine
)(newLine
threeLines : . newLine
.
.
.
.
:2-3 .
.
.
:3-3 newLine
threeLines .
-9-3
.
.
37 :
.
.
.
.
.
.
.
. .
.
.
.
.
-10-3
.
. sin
.
. pow
.
.
- :
def printTwice(bruce):
print bruce, bruce
38
bruce .
) ( . bruce
.
.
printTwice :
)'>>> printTwice('Spam
Spam Spam
)>>> printTwice(5
5 5
)>>> printTwice(3.14159
3.14159 3.14159
.
-
. printTwice :
)>>> printTwice('Spam'*4
SpamSpamSpamSpam SpamSpamSpamSpam
))>>> printTwice(math.cos(math.pi
-1.0 -1.0
printTwice .
-SpamSpamSpamSpam-SpamSpamSpamSpama 'Spam'*4-
'Spam'*4 . printTwice 'Spam'*4
SpamSpamSpamSpam .
printTwice .
:
.
) (michael ) (bruce .
printTwice bruce
.
-11-3
. :
) ( )
( .
:
catTwice cat .
:
40
>>> print cat
Traceback (most recent call last):
? File "<interactive input>", line 1, in
NameError: name 'cat' is not defined
printTwice bruce .
.
-12-3
.
.
.
.
:
1-3
. printTwice
catTwice catTwice __ __main
.
__ __main .
41 :
. part1 chant1
part2 chant2 . bruce cat.
__ __main .
printTwice cat
NameError :
Traceback (innermost last):
__File "test.py", line 13, in __main
)catTwice(chant1, chant2
File "test.py", line 5, in catTwice
)printTwice(cat
File "test.py", line 9, in printTwice
print cat
NameError: cat
.
.
.
. .
-13-3
. newLine
. :
)
(.
.3
newLine() + 7
.4
newLine printTwice
.
42
:5-3 .
.
-14-3
) function call (
.
) argument(
.
.
) return value (
.
.
) type conversion (
.
) type coercion (
.
) module(
.
) dot notation (
.
43 :
) function(
.
.
.
) function definition (
.
) flow of execution (
) parameter(
.
) local variable (
. .
) stack diagram (
.
) frame(
.
.
) traceback(
.
46
.
.
.
.
.
.
-1-4
) (
. ) (%
. :
>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
7 3 2 1.
. . x%y
x y .
.
x%10 ) x (10 x%100
x .
47 :
-2-4
) (true ) (false .
1 0 .
== :
>>> 5 == 5
1
>>> 5 == 6
0
(true) 1
5 6 (false) 0.
== . :
x != y x y x y
x > y x y
x < y x y
x >= y x y
x <= y x y
. = == .
= == . =>
) ( =< ) (
>= <= .
-3-4
or and : .not
. x > 0 and x < 10 x
.
48
n%2 == 0 or n%3 == 0 .
2 3 .
not x > y
x y not(x > y) .
. true .
>>> x = 5
>>> x and 1
1
>>> y = 0
>>> y and 1
0
.
0 .
-4-4
. .
if:
if x > 0:
"print "x is positive
if .
.
if
:
HEADER:
FIRST STATEMENT
...
LAST STATEMENT
49 :
) (Header ) (: .
.
. ) (
.
if
. )
( .
pass .
-5-4
if
. :
if x%2 == 0:
"print x, "is even
else:
"print x, "is odd
x 2 x
. .
true false .
.
. :
def printParity(x):
if x%2 == 0:
"print x, "is even
else:
"print x, "is odd
printParity x .
:
50
)>>> printParity(17
17 is odd
>>> y=21
)>>> printParity(y+1
22 is even
-6-4
.
:
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
"print x, "and", y, "are equal
elif else if . .
elif ) else ( :
if choice == 'A':
)(functionA
elif choice == 'B':
)(functionB
elif choice == 'C':
)(functionC
else:
"print "Invalid choice.
. false
.
.
.
-7-4
.
:
if x == y:
"print x, "and", y, "are equal
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y
.
if .
.
.
.
.
:
if 0 < x:
if x < 10:
"print "x is a positive single digit.
print .
and :
if 0 < x and x < 10:
"print "x is a positive single digit.
.
:
if 0 < x < 10:
"print "x is a positive single digit.
.
52
-8-4 return
return
. :
import math
def printLogarithm(x):
if x <= 0:
"print "Positive numbers only, please.
return
)result = math.log(x
print "The log of x is", result
printLogarithm x .
x 0
return .
. math
import.
-9-4
.
.
. :
def countdown(n):
if n == 0:
"!print "Blastoff
else:
print n
)countdown(n-1
countdown n . n
! Blastoff n countdown
53 :
)( n-1 .
)>>> countdown(3
countdown n=3 n 3
. . .
countdown n=2 n 2
. . .
countdown n=1 n 1
. . .
countdown n=0 n 0
! Blastoff .
countdown n=1 .
countdown n=2 .
countdown n=3 .
__ __main ) !!( .
:
3
2
1
!Blastoff
newLine threeLines :
def newline():
print
def threeLines():
)(newLine
)(newLine
)(newLine
2 106
. :
54
def nLines(n):
if n > 0:
print
)nLines(n-1
countdown n 0
n-1 .
) 1+(n-1 n
!
.
-10-4
11-3
. .
. .
1-4 countdown n=3
:
____main
countdown n 3
countdown n 2
countdown n 1
countdown n 0
1-4
__ __main .
__ __main . countdown
n . n=0 .
.
55 :
-11-4
.
.
:
def recurse():
)(recurse
. :
.
.
98 .
:3-4 .
-12-4
. .
. raw_input .
.
Enter raw_input
:
56
)( >>> input = raw_input
?What are you waiting for
>>> print input
?What are you waiting for
raw_input
raw_input . .
:
input :
\
. .
speed .
:
raw_input
.
57 :
-13-4
) modulus operator (
) (% .
.
) boolean expression (
) (true ) (false.
) comparison operator (
<= , == ,!= ,< ,> : =>
) logical operator (
. ) (: .
.
) conditional statement (
.
) condition(
.
) compound statement (
. ) (:
.
) block(
.
) body(
.
58
) branches(
.
) nested(
.
) recursion(
) (.
) base case (
.
) infinite recursion (
.
.
) prompt(
.
60
. .
.
.
-1-5
.
.
)e = math.exp(1.0
)height = radius * math.sin(angle
.
. :
import math
def area(radius):
temp = math.pi * radius**2
return temp
return return
. :
. .
:
def area(radius):
return math.pi * radius**2
temp .
return :
61 :
def absoluteValue(x):
if x < 0:
return -x
else:
return x
return
. .
) return (
.
return . :
def absoluteValue(x):
if x < 0:
return -x
elif x > 0:
return x
x
return . None
:
-2-5
.
.
.
62
.
.
) (x1, y1
) (x2, y2 . :
= distance ( ( ) + )
distance
. )( ) (
.
.
:
.
.
:
)>>> distance(1, 2, 4, 6
0.0
3 4
5 ) .(3-4-5
.
. .
- . -
63 :
x2 - x1 y2 - y1 .
dx dy :
3 ) 4 (0.0 .
. .
dx dy :
print .
.
) 25( .
math sqrt
.
. result
return .
64
.
.
.
:
.
.
.5 .
.
.6
.
:2-5 hypotenuse
. )
( . .
-3-5
. .
.
xc yc
xp yp .
. distance :
:
65 :
)result = area(radius
return result
area2 ) area (
. .
radius result
:
-4-5
. :
isDivisible .
/ . isDivisible 1 0
x y .
if
if :
:
)>>> isDivisible(6, 4
0
)>>> isDivisible(6, 3
1
:
if isDivisible(x, y):
"print "x is divisible by y
else:
"print "x is not divisible by y
if :
if isDivisible(x, y) == 1:
:4-5 ) isBetween(x, y, z x y z
1 0 .
-5-5
.
.
) .
67 :
. . . .
!(
)
.
( .
.
.
.
.
. :
:frabjuous frabjuous !
.
:
0! = 1
!)n! = n *(n-1
1 0 n n
.n-1 ! 3 3 ! 2 2 ! 1 1 ! 0.
6.
. .
factorial :
def factorial(n):
0 1 :
def factorial(n):
if n == 0:
return 1
68
) (
n-1 n :
def factorial(n):
if n == 0:
return 1
else:
)recurse = factorial(n-1
result = n * recurse
return result
countdown 9-4 .
3 :
3 0 n-1.
2 0 n-1
.
1 0
n-1.
0 0
1 .
) ( 1 n 1
.
) ( 1 n 2 .
) ( 2 n 3 6 .
.
1-5
:
____main
factorial n 0
1-5
69 :
.
result n recurse .
recurse result .
-6-5
. .
.
.
. math.cos math.exp
.
.
.
4-5 isDivisible
. ) (
.
.
) (
: n-1 n
n .
!
-7-5
:
70
def factorial(n):
if n == 0:
return 1
else:
)return n * factorial(n-1
.
.
fibonacci
:
fibonacci(0) = 1
fibonacci(1) = 1
)fibonacci(n) = fibonacci(n-1) + fibonacci(n-2
n
.
-8-5
factoial 1.5
n==0 . n .
n 0.5 . n 0.5
.
factorial
factorial .
. .
type ) (1
.
:
def factorial (n):
if type(n) != type(1):
"print "Factorial is only defined for integers.
return -1
elif n < 0:
"print "Factorial is only defined for positive integers.
return -1
elif n == 0:
return 1
else:
)return n * factorial(n-1
. )
( .
1 :
n
.
72
.
.
.
-9-5
) fruitful function (
.
) return value (
.
) temporary variable (
.
) dead code (
return .
None
return return
None .
) incremental development (
.
) scaffolding(
.
) composition(
.
73 :
) guardian(
.
76
.
.
.
.
-1-6
.
)
(.
bruce = 5
print bruce,
bruce = 7
print bruce
5 7 bruce 5
. 7 print
.
:
5
bruce
7
1-6
)=(
a = b .
77 :
aa=a7 .
7 = a a = 7 7 = a .
. aa=ab
a b .
:
a = 5
b = a # a and b are now equal
a = 3 # a and b are no longer equal
a b
) .
<- =(. :
.
.
-2-6 while
nLines countdown
. .
.
while.
countdown while:
def countdown(n):
while n > 0:
print n
n = n-1
"!print "Blastoff
.
while .
n > 0 n 1 . n
0 ! Blastoff .
78
while :
0 1
.7 (0) false while .
.8 (1) true 1.
.
. false
.
false
.
.
countdown n
0
. :
def sequence(n):
while n != 1:
print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1
n != 1 n 1
false.
n
. n 2
n*3+1 . ) sequence
( 3 :
3 10 5 16 8 4 2 1
79 :
n n
1 . n .
2 n 1
. 16
) n == 1(.
n .
-3-6
.
.
.
.
: !
. .
.
.
.
.
.
:
x = 1.0
while x < 10.0:
)print x, '\t', math.log(x
x = x + 1.0
' '\t tab .
80
.
print .
tab tab stop .
tab stop . tab
. :
1.0 0.0
2.0 0.69314718056
3.0 1.09861228867
4.0 1.38629436112
5.0 1.60943791243
6.0 1.79175946923
7.0 1.94591014906
8.0 2.07944154168
9.0 2.19722457734
e log
. 2
2 . :
1.0 0.0
2.0 1.0
3.0 1.58496250072
4.0 2.0
5.0 2.32192809489
6.0 2.58496250072
7.0 2.80735492206
8.0 3.0
9.0 3.16992500144
81 :
4 2 1 8 2 2
.
2
:
x = 1.0
while x < 100.0:
)print x, '\t', math.log(x)/math.log(2.0
x = x * 2.0
x
x .
:
1.0 0.0
2.0 1.0
4.0 2.0
8.0 3.0
16.0 4.0
32.0 5.0
64.0 6.0
tab
.
2 .
:3-6 :
Python
is a
programming language.
-4-6
.
. 1 6
.
2
:
i = 1
while i <= 6:
print 2*i, ' ',
i = i + 1
print
i .
print 2*i
. print .
print .
:
2 4 6 8 10 12
. .
-5-6
. :
printParity 5-4 isDivisible . 4-5
2
.
83 :
n :
def printMultiples(n):
i = 1
while i <= 6:
print n*i, '\t',
i = i + 1
print
.
2 n.
2
3 :
3 6 9 12 15 18
4 :
4 8 12 16 20 24
printMultiples
:
i = 1
while i <= 6:
)printMultiples(i
i = i + 1
printMultiples .
print .
:
1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36
84
-6-6
5-6
:
def printMultTable():
i = 1
while i <= 6:
)printMultiples(i
i = i + 1
.
.
.
.
.
-7-6
i
printMultiples printMultTable .
I printMultiples I printMultTable
.
.
.
i .
.
printMultTable 1
i 2
3
printMultiples 1
n 3 i 2
2-6
85 :
i printMultTable 1 6 .
3 . 4 .
printMultTable printMultiples i
. n .
printMultiples i 1 6 .
2 . i
printMultTable.
.
i j .
.
-8-6
.
printMultTable :
def printMultTable(high):
i = 1
while i <= high:
)printMultiples(i
i = i + 1
7 6 high . printMultTable
:
1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36
7 14 21 28 35 42
86
-
. printMultiples
.
high
) ( .
:
def printMultiples(n, high):
i = 1
while i <= high:
print n*i, '\t',
i = i + 1
print
def printMultTable(high):
i = 1
while i <= high:
)printMultiples(i, high
i = i + 1
) (
)
(printMultTable .
:
1 2 3 4 5 6 7
2 4 6 8 10 12 14
3 6 9 12 15 18 21
4 8 12 16 20 24 28
5 10 15 20 25 30 35
6 12 18 24 30 36 42
7 14 21 28 35 42 49
.
ab=ba .
!
printMultiples .
87 :
) printMultiples(i,ahigh )printMultiples(i,ai
:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
:4-6 printMultTable
.
-9-6
.
. :
.
.
.
.
.
-10-6
) multiple assignment (
.
88
) iteration(
.
) loop(
.
) infinite loop (
.
tab
.
) cursor(
.
) escape sequence (
/
.
) newline (
.
) loop variable (
.
) encapsulate(
) (.
89 :
) generalize(
) (
) ( .
.
) development plan (
.
.
92
.
.
.
.
.
-1-7
float int : ) string
( .
.
.
. .
:
.
.
.
-2-7
len :
">>> fruit = "banana
)>>> len(fruit
6
)length = len(fruit
]last = fruit[length !# ERROR
" "banana .
0 5 .
length :
)length = len(fruit
]last = fruit[length-1
. ] fruit[-1 fruit[-2]
.
-3-7 for
.
94
. .
while:
index = 0
while index < len(fruit):
]letter = fruit[index
print letter
index = index + 1
.
) index < len(fruit index
false .
len(fruit)-1 .
:1-7
.
char
.
-
- for .
Mack Lack Kack Jack
Pack OuackaNack Quack . :
"prefixes = "JKLMNOPQ
"suffix = "ack
:
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
:2-7 .
-4-7
. :
] [n:m n m
n m . .
. 1-7 :
fruit ""banana
index 0 1 2 3 4 5 6
1-7
) (
. :
96
">>> fruit = "banana
]>>> fruit[:3
''ban
]>>> fruit[3:
''ana
] s[:
-5-7
:
if word == "banana":
"!print "Yes, we have no bananas
. . :
.
.
!
-6-7
][
. :
97 :
! jello,aworld
:
TypeError: object doesn't support item assignment.
.
:
greeting .
.
-7-7 find
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1
find ][ .
.
1 .
return .
str[index] == ch .
1 .
98
3eureka
.
:3-7 find
.
-8-7
' 'a :
"fruit = "banana
count = 0
for char in fruit:
if char == 'a':
count = count + 1
print count
.
' 'a .
count ' 'a.
:4-7 counterLetter
.
:5-7
find .
-9-7 string
string .
:
-3
99 :
string find .
:
.
- .
find .
string.find .
:
b 1 2 )
2 (.
-10-7
. string .
100
string.lowercase
. string.uppercase .
:
find .
) find(lowercase, ch 1 ch
:
def isLower(ch):
return string.find(string.lowercase, ch) != -1
in
:
def isLower(ch):
return ch in string.lowercase
. :
def isLower(ch):
'return 'a' <= ch <= 'z
ch a z .
:6-7 .
string :
.
. string.whitespace
(\t) tab space ) (\n.
-11-7
) index(
.
) traverse(
.
) slice(
.
) immutable(
.
) counter(
.
) whitespace(
.
string.whitespace .
104
.
.
. .
. .
- -
. -
.
-1-8
)] [( :
.
.
) ( :
) .
(
:
)>>> range(1,5
][1, 2, 3, 4
105 :
range
.
.
range .
:
)>>> range(10
][0, 1, 2, 3, 4, 5, 6, 7, 8, 9
. 1 10 2:
.
][ .
.
-2-8
)][( . 0
:
]print numbers[0
numbers[1] = 5
106
.
numbers
123 5.
:
]>>> numbers[3-2
5
]>>> numbers[1.0
TypeError: sequence index must be integer
>>> numbers[2] = 5
IndexError: list assignment index out of range
]>>> numbers[-1
5
]>>> numbers[-2
17
]>>> numbers[-3
IndexError: list index out of range
] numbers[-1 ] numbers[-2
] numbers[-3 .
:
i = 0
while i < 4:
]print horsemen[i
i = i + 1
107 :
while 0 4 . i 4
. i 2 1 0 3
.
i i
. .
-3-8
len .
.
. :
i = 0
while i < len(horsemen):
]print horsemen[i
i = i + 1
i len(horsemen)-1
. i ) len(horsemen
. ) len(horsemen .
)(
. :
:1-8 .
len
-4-8
in .
10-7 :
108
]'>>> horsemen = ['war', 'famine', 'pestilence', 'death
>>> 'pestilence' in horsemen
1
>>> 'debauchery' in horsemen
0
-5-8 for
for 3-7 .
for :
i = 0
while i < len(LIST):
]VARIABLE = LIST[i
BODY
i = i + 1
for i .
for:
: )( horseman )(
) horsemen( horseman .
109 :
for :
0 19 .
.
-6-8
+ :
>>> ]a = [1, 2, 3
>>> ]b = [4, 5, 6
>>> c = a + b
>>> print c
[1, ]2, 3, 4, 5, 6
* :
>>> [0] * 4
[0, ]0, 0, 0
>>> [1, 2, 3] * 3
[1, ]2, 3, 1, 2, 3, 1, 2, 3
] [0 4 ] [1,2,3 3 .
-7-8
4-7 :
-8-8
.
:
-9-8
.
.
del :
) (
.
-10-8
:
"a = "banana
"b = "banana
a b " "banana
. :
a ""banana a
""banana
b ""banana b
1-8
a b
. .
.
id .
a b :
112
)>>> id(a
135044008
)>>> id(b
135044008
.
a b .
.
:
]>>> a = [1, 2, 3
]>>> b = [1, 2, 3
)>>> id(a
135045528
)>>> id(b
135041704
a ] [ 1, 2, 3
b ] [ 1, 2, 3
2-8
:
a b .
-11-8
:
]>>> a = [1, 2, 3
>>> b = a
3-8:
a
] [ 1, 2, 3
b
3-8
113 :
a b .
:
>>> b[0] = 5
>>> print a
][5, 2, 3
.
.
.
.
-12-8
) ( .
.
:
>>> ]a = [1, 2, 3
>>> ]b = a[:
>>> print b
[1, ]2, 3
a .
.
a b :
>>> b[0] = 5
>>> print a
][1, 2, 3
:2-8 a b .
114
-13-8
. head :
def head(list):
]return list[0
list numbers .
____main numbers
] [ 1, 2, 3
head list
4-8
:
.
.
deleteHead :
def deleteHead(list):
]del list[0
:
. tail
:
def tail(list):
]return list[1:
tail :
rest numbers .
-14-8
.
3 :
:
]>>> list[3][1
20
)][(
.
116
-15-8
. :
1 2 3
4 5 6
matrix .
:
]>>> matrix[1
][4, 5, 6
]>>> matrix[1][1
5
.
.
. .
-16-8
string .
split .
:
. ' 'ai :
.
join split .
:
split join :
-17-8
) list(
.
) element (
) ( . .
) sequence(
.
118
) nested list (
.
) list traversal (
.
) object(
.
) aliases(
.
) clone(
.
.
) delimiter(
) ( .
120
:
.
.
.
.
-1-9
.
:
)>>> t1 = ('a',
)>>> type(t1
>'<type 'tuple
)' ('a :
)'>>> t2 = ('a
)>>> type(t2
>'<type 'string
. :
121 :
]>>> tuple[1:3
)'('b', 'c
-2-9
.
. a:b
>>> temp = a
>>> a = b
>>> b = temp
.
:
>>> a, b = b, a
.
.
. .
122
>>> a, b, c, d = 1, 2, 3
ValueError: unpack tuple of wrong size
-3-9
.
:
)a, b = swap(a, b
swap .
swap :
swap :
)swap(a, b
a x . x swap x
a __ __main . y
b.
. .
:1-9
.
123 :
-4-9
.
.
. .
.
.
. .
random random 0.0 1.0
. random
. :
import random
for i in range(10):
)(x = random.random
print x
-5-9
. randomList
. n
124
. .
:
def randomList(n):
s = [0] * n
for i in range(n):
)(s[i] = random.random
return s
.
:
)>>> randomList(8
[0.15156642489, 0.498048560109, 0.810894847068, 0.360371157682,
]0.275119183077, 0.328578797631, 0.759199803101, 0.800367163582
random .
.
.
.
-6-9
.
. 8-7
.
.
:
125 :
count = 0
for char in fruit:
if char == 'a':
count = count + 1
print count
count = 0
for num in list:
if low < num < high:
count = count + 1
print count
. .
.
-7-9
inBucket .
:
)low = inBucket(a, 0.0, 0.5
)high = inBucket(a, 0.5, 1
126
.
. numBuckets
1/numBuckets .
. i 1
numBuckets-1 :
.
) bucketWidth ( .
numBuckets = 8 :
0.0 to 0.125
0.125 to 0.25
0.25 to 0.375
0.375 to 0.5
0.5 to 0.625
0.625 to 0.75
0.75 to 0.875
0.875 to 1.0
)(
. 0.0 1.0 .
.
.
127 :
. .
inBucket i :
numBuckets = 8
buckets = [0] * numBuckets
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
)buckets[i] = inBucket(list, low, high
print buckets
1000 :
125 .
.
:4-9
.
-8-9
.
inBucket .
.
. .
i bucketWidth
. 0.0 1.0
.
bucketWidth . .
128
numBuckets = 8
buckets = [0] * numBuckets
for i in list:
)index = int(i * numBuckets
buckets[index] = buckets[index] + 1
int .
)
(len(buckets)-1
buckets histogram
.
:5-9 histogram
histogram .
-9-9
) immutable type (
.
.
) mutable type (
.
. .
129 :
) tuple(
.
.
) tuple assignment (
.
.
) deterministic(
.
) pseudorandom (
.
) patern matching (
.
histogram
.
132
-
.
.
.
. .
. }{ .
}{ = >>> eng2sp
'>>> eng2sp['one'] = 'uno
'>>> eng2sp['two'] = 'dos
eng2sp
. :
. ) (:
. . -
.
-
:
eng2sp :
- !
:
]'>>> print eng2sp['two
''dos
-1-10
del - .
:
>>> inventory['pears'] = 0
>>> print inventory
}{'oranges': 525, 'apples': 430, 'pears': 0, 'bananas': 312
len - :
)>>> len(inventory
4
134
-2-10
-
. keys
) keys(eng2sp
)( eng2sp.keys :
)(>>> eng2sp.keys
]'['one', 'three', 'two
) (keys
) (eng2sp . .
. keys
eng2sp .
values keys
:
)(>>> eng2sp.values
]'['uno', 'tres', 'dos
items ) -
( :
)(>>> eng2sp.items
])'[('one','uno'), ('three', 'tres'), ('two', 'dos
.
.
.
has_key (1) true
:
)'>>> eng2sp.has_key('one
1
)'>>> eng2sp.has_key('deux
0
135 :
.
:
)'>>> has_key('one
NameError: has_key
-3-10
.
.
copy . opposites
:
copy opposites :
-4-10
14-8 .
:
136
0 0 0 1 0
0 0 0 0 0
0 2 0 0 0
0 0 0 0 0
0 0 0 3 0
0 :
matrix = [ [0,0,0,1,0],
[0,0,0,0,0],
[0,2,0,0,0],
[0,0,0,0,0],
] ][0,0,0,3,0
.
:
-
. .
][ :
]matrix[0,3
1
.
.
. 0
:
]>>> matrix[1, 3
)KeyError: (1, 3
137 :
get :
)>>> matrix.get((0,3), 0
1
get
:
)>>> matrix.get((1,3), 0
0
get
!
-5-10
fibonacci 7-5
.
. fibonacci(20)
) fibonacci(30 1 ) fibonacci(40
.
fibonacci n = 4 :
fibonacci
n 4
fibonacci fibonacci
n 3 n 2
fibonacci fibonacci
1-10
n 1 n 0
138
. fibonacci na=a4
fibonacci n = 3 n = 2 . fibonacci na=a3
fibonacci n = 2 n = 1 . ...
) fibonacci(0 ) fibonacci(1 .
.
.
. fibonacci :
def fibonacci(n):
if previous.has_key(n):
]return previous[n
else:
)newValue = fibonacci(n-1) + fibonacci(n-2
previous[n] = newValue
return newValue
previous .
0 : 1 1 1 .
fibonacci
.
.
.
fibonacci ) fibonacci(40
. ) fibonacci(50
:
)>>> fibonacci(50
OverflowError: integer addition
139 :
20,365,011,074 .
) (integer
. .
-6-10
long int
. long int . L
:
)>>> type(1L
>'<type 'long int
)>>> long(1
1L
)>>> long(3.9
3L
)'>>> long('57
57L
long int
fibonacci :
previous fibonacci .
long int long int .
-7-10
7 .
histogram .
.
.
histogram :
}{ = >>> letterCounts
>>> for letter in "Mississippi":
... letterCounts[letter] = letterCounts.get (letter, 0) + 1
...
>>> letterCounts
}{'M': 1, 's': 4, 'p': 2, 'i': 4
. )
( .
.
histogram .
items sort :
items sort
. extend append reverse .
-8-10
) dictionary(
- .
.
141 :
) key(
.
) key-value pair -(
.
) method(
.
) invoke(
.
) call graph (
.
) hint(
.
) overflow(
.
144
.
.
. CD
.
)(
.
.
PDF .
.
. .
. .
.
.
.
. f
:
)">>> f = open("test.dat","w
>>> print f
><open file 'test.dat', mode 'w' at fe820
open . ) (
. w ) (write .
test.dat
.
) (
.
write :
:
)(>>> f.close
. "r"
) (read :
)">>> f = open("test.dat","r
)">>> f = open("test.cat","r
'IOError: [Errno 2] No such file or directory: 'test.cat
read .
:
time to .
read :
)">>> f = open("test.dat","r
)>>> print f.read(5
Now i
read
read :
>>>
146
50 .
file :
break .
.
while 1 true .
break text
.
-1-11
.
.
:
)">>> f = open("test.dat","w
)">>> f.write("line one\nline two\nline three\n
)(>>> f.close
readline
:
147 :
)">>> f = open("test.dat","r
)(>>> print f.readline
line one
>>>
readlines :
012 .
readline readlines :
filterFile .
# :
continue .
text
.
148
-2-11
write
. str:
>>> x = 52
))>>> f.write (str(x
% . %
.
.
.
" "%d
. d decimal:
>>> cars = 52
>>> "%d" % cars
''52
' '52 52 .
.
:
>>> cars = 52
>>> "In July we sold %d cars." % cars
''In July we sold 52 cars.
" "%f
" "%s :
.
:
149 :
.
:
>>> "%6d" % 62
' '62
>>> "%12f" % 6.1
' '6.100000
.
:
>>> "%-6d" % 62
'62 '
.
.
.
:
def report (wages):
)(students = wages.keys
)(students.sort
for student in students:
)]print "%-20s %12.02f" % (student, wages[student
:
150
}>>> wages = {'mary': 6.23, 'joe': 5.45, 'joshua': 4.25
)>>> report (wages
joe 5.45
joshua 4.25
mary 6.23
21
.
-3-11
) ( .
.
)( :
)">>> f = open("C:\\programming\\Python\\Tests\\test1.dat","r
)(>>> print f.readline
This is a test.
C programming Python
Tests test1.dat .
This is a test. )( readline .
"\"
"\" .
"\"
.
Pickling -4-11
.
str :
.
.
:
)(>>> f.readline
']'12.3[1, 2, 3
PicklingPickling .
. pickle .
pickle :
dump
:
)>>> pickle.dump(12.3, f
)>>> pickle.dump([1,2,3], f
)(>>> f.close
)">>> f = open("test.pck","r
)>>> x = pickle.load(f
>>> x
12.3
)>>> type(x
>'<type 'float
)>>> y = pickle.load(f
>>> y
][1, 2, 3
)>>> type(y
>'<type 'list
load
.
152
-5-11
.
.
:
][ = >>> a
]>>> print a[5
IndexError: list index out of range
}{ = >>> b
]'>>> print b['what
KeyError: what
:
.
.
. try except
.
.
:
except try .
except
.
: exists
true false :
def exists(filename):
try:
)f = open(filename
)(f.close
return 1
except:
return 0
except .
.
.
17 . 17
) ( :
raise : .
BadNumberError .
inputNumber
:
)( >>> inputNumber
Pick a number: 17
BadNumberError: 17 is a bad number
.
154
:1-11 inputNumber
BadNumberError .
-6-11
) file(
CD-ROM
.
) directory(
) (folder .
break statement
.
) text file (
.
continue statement
.
.
) format operator (
%
.
) format string (
.
155 :
) format sequence (
%
.
) path(
.
pickling
.
) exception(
.
) handle(
try . except
158
.
.
- .
.
-1-12 -
. -
:.
.
)( .
.
) (0a,0 .
. .
.
.
.
:
class Point:
pass
)
.(import
) 4-4 (.
Point . pass .
.
159 :
Point Point .
. .
Point Point :
)(blank = Point
-2-12
:
math.pi
. string.uppercase .
.
:
blank x 3.0
y 4.0
1-12
blank Point .
.
:
blank.x blank x .
x . x x .
.
:
) (3.0, 4.0
25.0 .
blank :
:1-12 Point id
.
-3-12
. :
def printPoint(p):
')' print '(' + str(p.x) + ', ' + str(p.y) +
printPoint
. ) printPoint(blank ) (3.0, 4.0.
161 :
-4-12
.
== . :
p1 p2 . p1
p2 :
>>> p2 = p1
>>> p1 == p2
1
.
samePoint
:
def samePoint(p1, p2):
)return (p1.x == p2.x) and (p1.y == p2.y
samePoint :
>>> = p1 )(Point
>>> p1.x = 3
>>> p1.y = 4
>>> = p2 )(Point
162
>>> p2.x = 3
>>> p2.y = 4
)>>> samePoint(p1, p2
1
-5-12
.
.
.
: ) ( ) (
.
. -
. :
class Rectangle:
pass
:
)(box = Rectangle
box.width = 100.0
box.height = 200.0
Rectangle .
- !
)(box.corner = Point
box.corner.x = 0.0
box.corner.y = 0.0
box . box.corner.x
corner corner x
.
163 :
2-12
-6-12
. findCenter Rectangle
Point Rectangle
:
def findCenter(box):
)(p = Point
p.x = box.corner.x + box.width/2.0
p.y = box.corner.y + box.height/2.0
return p
box
:
-7-12
.
width height
:
box.width = box.width + 50
box.height = box.height + 100
164
dwidth dheight
. Rectangle
.
Rectangle bob growRect
:
>>> )(bob = Rectangle
>>> bob.width = 100.0
>>> bob.height = 200.0
>>> )(bob.corner = Point
>>> bob.corner.x = 0.0
>>> bob.corner.y = 0.0
>>> )growRect(bob, 50, 100
-8-12
.
.
.
. copy
copy :
165 :
copy copy
Point p1 . p2
.
Point copy
. .
Rectangle Point
. Point Rectangle
Rectangle Point .
b1 ) ( b2
. :
3-12
. growRect
Rectangle moveRect
. .
copy deepcopy
.
:
)>>> b2 = copy.deepcopy(b1
166
b1 b2 .
deepcopy growRect
Rectangle Rectangle . Rectangle
:
-9-12
) class(
.
.
) instance(
.
) object(
.
) instantiate(
.
) constructor(
.
167 :
) attribute(
.
) shallow equality (
.
) deep equality (
.
) shallow copy (
copy copy .
) deep copy (
deepcopy copy .
170
.
.
.
- .
.
-1-13
- Time
. :
class Time:
pass
Time
:
)(time = Time
time.hours = 11
time.minutes = 59
time.seconds = 30
Time :
time hour 11
minute 59
second 30
1-13
-2-13
addTime
. : .
addTime :
Time
.
.
. Time:
currentTime breadTime .
addTime .
printTime 2-14 :
12:49:30 .
.
.
.
:
return sum
.
.
-3-13
.
.
.
increment Time
.
:
173 :
.
seconds
seconds
60 . while if:
:3-13 .
:4-13 increment
.
-4-13
.
.
174
.
.
.
.
-5-13
.
) (
.
-
-
.
.
Time 60! second
minute 60 hour 3600.
addTime increment
60 .
- Time
. Time :
def convertToSeconds(t):
minutes = t.hours * 60 + t.minutes
seconds = minutes * 60 + t.seconds
return seconds
Time:
175 :
def makeTime(seconds):
)(time = Time
time.hours = seconds/3600
seconds = seconds - time.hours * 3600
time.minutes = seconds/60
seconds = seconds - time.minutes * 60
time.seconds = seconds
return time
.
addTime :
.
) (.
increment :5-13 .
-6-13
60 10
. .
60
) convertToSeconds (makeTime
.
. Time
.
. 150-12 .
5 0 .
.
176
) ( )
(.
-7-13
.
. .
.
. .
.
.
n 9 ) (n-1 10-n .
9 . 6 9
:
6-1 5 10-6 4 54
!
.
.
.
.
.
.
. .
.
177 :
-8-13
) pure function (
.
.
) modifier (
.
.
) prototype development (
.
) planned development (
.
) algorithm(
.
180
- .
.
C++ .
-1-14
.
:
.
.
Time 13
. Point Rectangle
.
.
.
Time
. Time
. .
values keys .
.
:
181 :
.
.
.
.
.
.
printTime -2-14
13 Time printTime
:
class Time:
pass
def printTime(time):
print str(time.hours) + ":" +
str(time.minutes) + ":" +
)str(time.seconds
printTime
. .
class Time:
def printTime(time):
print str(time.hours) + ":" +
str(time.minutes) + ":" +
)str(time.seconds
printTime :
182
.
currentTime time .
self
.
printTime(currentTime)
: printTime
.
.
)( currentTime.printTime : currenttime .
.
.
-3-14
) increment (3-13 .
:
class Time:
#previous method definitions here...
.
. increment :
)(currentTime = Time
currentTime.hours = 9
currentTime.minutes = 14
currentTime.seconds = 30
)currentTime.increment(500
self
seconds 500 .
-4-14
after Time .
self . :
class Time:
#previous method definitions here...
def after(self, time2):
if self.hour > time2.hour:
return 1
if self.hour < time2.hour:
return 0
:
if doneTime.after(currentTime):
"print "The bread will be done after it starts.
-5-14
.
string.find .
- .
find find.string .
7-7:
start 0
. find
:
:2-14 end
.
: . end ) len(str
. .
find str .
-6-14
.
__ __init ) init (.
Time :
class Time:
def __init__(self, hours=0, minutes=0, seconds=0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
self.hours hours .
.
Time
init :
)>>> currentTime = Time(9, 14, 30
)(>>> currentTime.printTime
>>> 9:14:30
:
)>>> currentTime = Time (9, 14
)(>>> currentTime.printTime
>>> 9:14:0
-7-14 Point
Point 1-12 :
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
')' return '(' + str(self.x) + ', ' + str(self.y) +
x y .
0 .
__str__ Point .
str str .
)>>> p = Point(3, 4
)>>> str(p
')'(3, 4
Point __ __str
__ __str print :
)>>> p = Point(3, 4
>>> print p
)(3, 4
187 :
__ __init
__ __str
.
-8-14
- . .
.
+ __ __add :
class Point:
# previously defined methods here...
.
other self . Point
Point x y .
+ Point __ __add :
p1+p2 ) p1.__add__(p2
.
____mul .
__ __rmul .
* Point __ __mul
Point .
:
* Point
__ __mul :
Point .
other __rmul__
.
:
)>>> p1 = Point(3, 4
)>>> p2 = Point(5, 7
>>> print p1 * p2
43
>>> print 2 * p2
)(10, 14
Point p2*2
__ __mul 2 .
__ __mul x other
:
>>> print p2 * 2
'AttributeError: 'int' object has no attribute 'x
.
. .
189 :
-9-14
.
.
.
.
) multadd (
.
:
x y z
. :
Point:
>>> p1 = Point(3, )4
>>> p2 = Point(5, )7
>>> print multadd )(2, p1, p2
)(11, 15
>>> print multadd )(p1, p2, 1
44
Point Point
.
.
190
frontAndBack
:
def frontAndBack(front):
import copy
)back = copy.copy(front
)(back.reverse
)print str(front) + str(back
copy reverse
. .
frontAndBack :
. Point
.
:
.
def reverse(self):
self.x , self.y = self.y, self.x
Point frontAndBack:
)>>> p = Point(3, 4
)>>> frontAndBack(p
)(3, 4)(4, 3
191 :
-10-14
) object-oriented programming (
.
) method(
.
) override (
.
.
) initialization method (
.
) operator overloading (
) > < * - + ( -
.
) dot product (
Point
.
192
) scalar multiplication (
Point
.
) polymorphic (
.
.
194
.
.
-1-15
.
.
if while if .
.
) ( .
.
Card
.
-2-15 Card
.
.
. .
:
Ace King 2 .
195 :
) rank : ( ) suit ( .
. " "Spades
" "Queen .
) (rank ) (suit .
.
.
. :
Spades 3
Hearts 2
Diamonds 1
Clubs 0
.
:
Jack 11
Queen 12
King 13
) (
. Card :
class Card:
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank
.
196
3 Clubs :
)threeOfClubs = Card(0,3
0 Clubs .
-3-15 ____str
Card
) (integer .
.
:
class Card:
]"suitList = ["Clubs", "Diamonds", "Hearts", "Spades
rankList = ["narf", "Ace", "2", "3", "4", "5", "6", "7",
]""8", "9", "10", "Jack", "Queen", "King
def __str__(self):
return (self.rankList[self.rank] + " of " +
)]self.suitList[self.suit
suitList Card .
Card :
. " "JacksofsDiamonds
" "JacksofsSwirly Whales :
-4-15
)== < > (
.
- __ __cmp
. __cmp__ self other
1 -1 0 .
. .
198
.
.
. 3 Clubs 2 Clubs
3 Diamonds 3 Clubs . 3 Clubs 2
Diamonds .
. .
Clubs
Diamonds .
__ __cmp :
Ace )1( 2 .
-5-15
Card Deck .
Deck
.
Deck . Cards
52 :
199 :
class Deck:
def __init__(self):
][ = self.cards
for suit in range(4):
for rank in range(1, 14):
))self.cards.append(Card(suit, rank
.
0 3 1 13 .
52
. Card
cards . append ) ( .
-6-15
. Deck Card :
class Deck:
...
def printDeck(self):
for card in self.cards:
print card
) (...
. printDeck __ __str Deck.
__ __str .
.
__ __str Deck .
:
200
class Deck:
...
def __str__(self):
"" = s
for i in range(len(self.cards)):
"s = s + " "*i + str(self.cards[i]) + "\n
return s
. self.cards
i
.
.
print __ __str
. str __ __str
.
s . s
. s
. s Deck
:
.
201 :
52
.
-7-15
.
randrange random
. a randrange b a-<=-x-<-b
. b
.
:
))random.randrange(0, len(self.cards
. .
:
class Deck:
...
def shuffle(self):
import random
)nCards = len(self.cards
for i in range(nCards):
)j = random.randrange(i, nCards
]self.cards[i], self.cards[j]=self.cards[j], self.cards[i
52
nCards .
. ) (i ) (j .
2-9 :
:2-15 .
202
-8-15
Deck removeCard .
(1) true (0) false
:
class Deck:
...
def removeCard(self, card):
if card in self.cards:
)self.cards.remove(card
return 1
else:
return 0
) (
in true .
__ __cmp . ____cmp
Card removeCard
.
. pop
:
class Deck:
...
def popCard(self):
)(return self.cards.pop
pop .
.
isEmpty .
true :
class Deck:
...
def isEmpty(self):
)return (len(self.cards) == 0
203 :
-9-15
) encode (
.
) class attribute (
.
.
) accumulator(
.
206
Card .
.
-1-16
.
.
.
. .
.
.
.
.
.
.
.
) ( .
.
Old Maid
.
.
-2-16
.
.
.
207 :
.
. Poker
. Bridge
.
. Hand Deck
.
:
class Hand(Deck):
pass
Hand Deck .
Hand
name cards . name
name . cards .
:
class Hand(Deck):
def __init__(self, name=""):
][ = self.cards
self.name = name
.
removeCard Hand Deck
addCard :
class Hand(Deck):
...
def addCard(self,card):
)self.cards.append(card
) (...
. append .
208
-3-16
Hand Deck .
Hand Deck
Deck .
deal .
.
deal . ) (
.
:
class Deck:
...
def deal(self, hands, nCards=999):
)nHands = len(hands
for i in range(nCards):
if self.isEmpty(): break # break if out of cards
)(card = self.popCard # take the top card
?hand = hands[i % nHands] # whose turn is next
)hand.addCard(card # add the card to the hand
nCards :
.
i 0 nCards-1 .
pop . .
) (% )
( . i
i%nHands ) (0.
209 :
-4-16
printDeck __ __str
Deck . :
Hand .
__ __str Hand Deck
:
)class Hand(Deck
...
def __str__(self):
s = "Hand " + self.name
if self.isEmpty():
"s = s + " is empty\n
else:
"s = s + " contains\n
)return s + Deck.__str__(self
s .
is-empty s . contains
Deck . Deck __ __str
self Deck .
) self Hand ( Deck
Hand Deck .
.
210
-5-16 CardGame
CardGame
:
class CardGame:
def __init__(self):
)(self.deck = Deck
)(self.deck.shuffle
.
CardGame
. Old Maid .
.
4 Clubs 4 Spades Jack . Hearts
Jack Diamonds .
Queen Clubs Queen
Spades .
. .
.
) (
.
. .
Queen Spades .
.
. Old Maid
.
211 :
-6-16 OldMaidHand
OldaMaid Hand
. OldMaidHand
Hand removeMatches :
class OldMaidHand(Hand):
def removeMatches(self):
count = 0
]originalCards = self.cards[:
for card in originalCards:
)match = Card(3 - card.suit, card.rank
if match in self.cards:
)self.cards.remove(card
)self.cards.remove(match
)print "Hand %s: %s matches %s" % (self.name,card,match
count = count + 1
return count
. self.cards
.
.
. ) ( .
3-crad.suit ) Club (0 ) Spade (1 Heart
) (2 . .
.
removeMatches :
>>> hand.removeMatches()
Hand frank: 7 of Spades matches 7 of Clubs
Hand frank: 8 of Spades matches 8 of Clubs
Hand frank: 10 of Diamonds matches 10 of Hearts
>>> print hand
Hand frank contains
Ace of Spades
2 of Diamonds
6 of Hearts
Queen of Clubs
7 of Diamonds
5 of Clubs
Jack of Diamonds
OldMaidGame -7-16
OldMaidGame .
play CardGame
.
OldMaidGame CardGame __ init__
:
class OldMaidGame(CardGame):
def play(self, names):
# remove Queen of Clubs
self.deck.removeCard(Card(0,12))
removeAllMatches .
: removeMatches
class OldMaidGame(CardGame):
...
def removeAllMatches(self):
count = 0
for hand in self.hands:
count = count + hand.removeMatches()
return count
count
.
.
214
turn . 0
. numHand 0
.
playOneTurn .
:
class OldMaidGame(CardGame):
...
def playOneTurn(self, i):
if self.hands[i].isEmpty():
return 0
)neighbor = self.findNeighbor(i
)(pickedCard = self.hands[neighbor].popCard
)self.hands[i].addCard(pickedCard
print "Hand", self.hands[i].name, "picked", pickedCard
)(count = self.hands[i].removeMatches
)(self.hands[i].shuffle
return count
0 .
.
.
findNeighbor
:
class OldMaidGame(CardGame):
...
def findNeighbor(self, i):
)numHands = len(self.hands
for next in range(1,numHands):
neighbor = (i + next) % numHands
if not self.hands[neighbor].isEmpty():
return neighbor
215 :
None findNeighbor
.
.( )
. . printHand
10)
. (
:
. Jeff
-8-16
( )inheritance
.
( ) parent class
.
217 :
) child class (
.
220
15 16 Card
. .
.
.
-1-17
) 8-12 ( .
.
. .
.
:
None
.
-2-17 Node
____str
:
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
)return str(self.cargo
221 :
.
) (cargo ) (next None .
.
str .
Node .
.
:
1-17
None .
2-17.
222
2-17
.
.
-3-17
. .
.
.
printList
.
def printList(node):
while node:
print node,
node = node.next
print
.
)>>> printList(node1
1 2 3
printList
. next .
node
.
3-17 list node .
223 :
node
3-17
:1-17
] .[1,a2,a3 printList
.
-4-17
.
.
.1 : ) ( )
(
.2 .
.3 .
) 2 (
. -
- .
.
None :
224
def printBackward(list):
if list == None: return
head = list
tail = list.next
)printBackward(tail
print head,
.
.
.
printList :
)>>> printBackward(node1
3 2 1
.
printList printBackward
.Node
None
None .
.
printBackward
.
.
-5-17
) (
.
:
list
cargo 1 cargo 2
4-17
225 :
printList
printBackward .
.
.
.
printList
PrintBackward . :
.
.
. .
-6-17
printBackward :
head = list
tail = list.next
head list .
. head
list .
.
.
.
node list
. .
printBackward head tail
:
def printBackward(list):
if list == None: return
)printBackward(list.next
print list,
226
. printBackward
print
.
:
-7-17
. )
( .
.
:
def removeSecond(list):
if list == None: return
first = list
second = list.next
# make the first node refer to the third
first.next = second.next
# separate the second node from the rest of the list
second.next = None
return second
.
:
>>> )printList(node1
1 2 3
>>> )removed = removeSecond(node1
>>> )printList(removed
2
>>> )printList(node1
1 3
:
227 :
first second
5-17
-8-17
.
] [3, 2, 1 printBackward 3, 2,
.
printBackwardNicely:
def printBackwardNicely(list):
print "[",
if list != None:
head = list
tail = list.next
)printBackward(tail
print head,
print "]",
.
printBackwardNicely printBackward
. printBackwardNicely
printBackward .
228
-9-17 LinkedList
.
.
LinkedList .
. LinkedList
Node :
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
LinkedList
printBackwardNicely
LinkedList:
class LinkedList:
...
def printBackward(self):
print "[",
if self.head != None:
)(self.head.printBackward
print "]",
class Node:
...
def printBackward(self):
if self.next != None:
tail = self.next
)(tail.printBackward
print self.cargo,
printBackwardNicely .
printBackward ) Node (
) LinkedList( . self.head.printBackward
self.head Node.
229 :
LinkedList
. addFirst LinkedList .
:
class LinkedList:
...
def addFirst(self, cargo):
)node = Node(cargo
node.next = self.head
self.head = node
self.length = self.length + 1
-10-17
.
.
. length LinkedList
.
.
.
. addFirst
length .
.
.
230
-11-17
) embedded reference (
.
) linked list (
.
) node(
.
) cargo(
.
) link(
.
) precondition(
)( .
) wrapper(
.
231 :
) helper(
.
) invariant(
)( )
(.
234
.
.
.
-1-18
) .
(. Card
.
.
(Abstract Data Type) ADT
) ( .
.
.
ADT
.
ADT
.
ADT
. ADT ADT
- - ADT - -
.
235 :
-2-18
ADT .
.
. ADT
. :
__ :__init .
:push .
:pop .
.
:isEmpty .
-3-18
.
ADT
.
ADT .
.
ADT :
class Stack:
def __init__(self):
][ = self.items
def pop(self):
)(return self.items.pop
def isEmpty(self):
)][ == return (self.items
236
items
. items .
push items .
pop
.
items isEmpty
.
.
.
.
-4-18
) (generic .
. :
isEmpty pop :
+ 45 54 .
.
.
printBackward 4-17 .
printBackward
printBackward
237 :
.
Stack
.
-5-18 postfix
. 1 + 2 infix .
postfix . postfix
. 1 2 +
postfix
postfix :
) ( .
- push.
-
.
.
.
:1-18 * 1 2 + 3 .
postfix :
. infix
(1n+n2)n*n3.
:2-18 postfix 1 + 2 * 3.
238
-6-18
. - -
) ( . 1 .
split string (regular expression) re
. string.split )(delimiter
. :
.
.
re.split
. .
] [A-z ] [0-9 . ^
] [^0-9 .
postfix :
>>> import re
)">>> re.split("([^0-9])", "123+456*/
]'' ['123', '+', '456', '*', '', '/',
string.split .
.
123 456 * / .
.
-7-18 postfix
postfix
) ( .
+ * :
239 :
def evalPostfix(expr):
import re
)tokenList = re.split("([^0-9])", expr
)(stack = Stack
for token in tokenList:
if token == '' or token == ' ':
continue
if token == '+':
)(sum = stack.pop() + stack.pop
)stack.push(sum
elif token == '*':
)(product = stack.pop() * stack.pop
)stack.push(product
else:
))stack.push(int(token
)(return stack.pop
. .
.
.
postfix (56+47)*2 :
-8-18
ADT -
aADT - - ADT - .
ADT .
ADT
.
.
240
ADT
. .
.
-9-18
) client(
) ( ADT .
) provider(
) ( ADT .
) stack(
ADT .
) interface (
ADT .
) implementation(
.
) veneer(
ADT )
( .
.
infix
.
postfix
.
) parse(
.
) token(
.
244
ADT ADT .
ADT : .
.
.
.
.
FIFO ) .(First In, First Out
.
.
.
.
ADT ADT . :
FIFO ) (
.
ADT -1-19
ADT :
__ :__init .
:insert .
:remove .
.
:isEmpty .
-2-19
ADT
Node . :
245 :
class Queue:
def __init__(self):
self.length = 0
self.head = None
def isEmpty(self):
return (self.length == 0)
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length = self.length - 1
return cargo
-3-19
.
: .
remove .
. - .
.
insert .
. .
-
- .
-4-19
ADT - .
1-19 .
1-19
:
class ImprovedQueue:
def __init__(self):
self.length = 0
self.head = None
self.last = None
def isEmpty(self):
)return (self.length == 0
247 :
last .
- . .
last None remove
:
class ImprovedQueue:
...
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length = self.length - 1
if self.length == 0:
self.last = None
return cargo
.
insert remove -
.
:1-19 ADT .
ImprovedQueue
.
248
-5-19
ADT ADT .
:
__ :__init .
:insert .
:remove .
.
:isEmpty .
.
.
.
.
.
.
.
:
class PriorityQueue:
def __init__(self):
][ = self.items
def isEmpty(self):
][ == return self.items
isEmpty insert .
remove:
249 :
class PriorityQueue:
...
def remove(self):
maxi = 0
for i in range(1,len(self.items)):
if self.items[i] > self.items[maxi]:
maxi = i
]item = self.items[maxi
][ = ]self.items[maxi:maxi+1
return item
maxi ) (
. i .
maxi i .
for maxi .
. :
.
.
__ __cmp .
remove > __ __cmp
. __ __cmp
.
250
-6-19 Golfer
Golfer
.
__ __init __ __str :
class Golfer:
def __init__(self, name, score):
self.name = name
self.score= score
def __str__(self):
)return "%-16s: %d" % (self.name, self.score
__ __str
.
__ __cmp
. __cmp__ self other 1
other -1 0 .
class Golfer:
...
def __cmp__(self, other):
if self.score < other.score: return 1 # less is more
if self.score > other.score: return -1
return 0
Golfer :
:2-19 ADT
.
- . .
-7-19
) Queue(
ADT .
) Priority Queue (
ADT
.
) queueing policy (
.
FIFO
" ." First In First Out
.
) linked queue (
.
) constant time-(
.
) linear time-(
.
254
17 .
.
) ( .
)( .
) (cargo . :
tree
cargo 1
left right
cargo 2 cargo 3
left right left right
1-20
None .
) tree ( .
None .
!
- - : .
.
.
.
) /( )
/( .
.
255 :
.
.
:
None
.
-1-20
.
.
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
)return str(self.cargo
.
256
-2-20
:
.
:
def total(tree):
if tree == None: return 0
return total(tree.left) + total(tree.right) + tree.cargo
0 .
.
.
-3-20
.
. ) 1+2*3
infix( .
:
tree
cargo +
left right
cargo 1 cargo *
left right left right
1 2 + * .
) .
(.
257 :
.
.
prefix postfix infix .
.
-4-20
:
def printTree(tree):
if tree == None: return
print tree.cargo,
)printTree(tree.left
)printTree(tree.right
.
preorder
. :
postfix infix .
prefix .
.
.
:
258
def printTreePostorder(tree):
if tree == None: return
)printTreePostorder(tree.left
)printTreePostorder(tree.right
print tree.cargo,
1 2 3 * + postfix! postorder
.
inorder
:
def printTreeInorder(tree):
if tree == None: return
)printTreeInorder(tree.left
print tree.cargo,
)printTreeInorder(tree.right
1 + 2 * 3 infix .
.
infix .
inorder infix .
.
printTreePreorder :1-20
.
inorder
:
0 level .
. level+1
.
. :
)>>> printTreeIndented(tree
3
*
2
+
1
-5-20
infix
. (3+7)*9 :
+ 9
3 7
3-20
.
+ *
.
. (3+7)*9 :
]'['(', 3, '+', 7, ')', '*', 9, 'end
end .
260
:2-20
.
getToken
.
true false
:
def getToken(tokenList, expected):
if tokenList[0] == expected:
]del tokenList[0
return 1
else:
return 0
tokenList
.
getNumber . tokenList
getNumber
None :
def getNumber(tokenList):
]x = tokenList[0
if type(x) != type(0): return None
]del tokenList[0
)return Tree (x, None, None
getNumber .
tokenList .
:
getProduct
. .3*7
261 :
getProduct .
def getProduct(tokenList):
)a = getNumber(tokenList
if getToken(tokenList, '*'):
)b = getNumber(tokenList
)return Tree ('*', a, b
else:
return a
getNumber
a . * b a
.
a .
:
]'>>> tokenList = [9, '*', 11, 'end
)>>> tree = getProduct(tokenList
)>>> printTreePostorder(tree
* 9 11
]'>>> tokenList = [9, '+', 11, 'end
)>>> tree = getProduct(tokenList
)>>> printTreePostorder(tree
9
. .
3*5*13 .
) .3*(5*13 :
3 *
4-20 5 13
getProduct :
262
def getProduct(tokenList):
)a = getNumber(tokenList
if getToken(tokenList, '*'):
)b = getProduct(tokenList # this line changed
)return Tree ('*', a, b
else:
return a
*
.
.
:
.
. +
.
:
) ( .
.
getSum
+ :
def getSum(tokenList):
)a = getProduct(tokenList
if getToken(tokenList, '+'):
)b = getSum(tokenList
)return Tree ('+', a, b
else:
return a
9 * 11 + 5 * 7 :
]'>>> tokenList = [9, '*', 11, '+', 5, '*', 7, 'end
)>>> tree = getSum(tokenList
)>>> printTreePostorder(tree
9 11 * 5 7 * +
263 :
.
.
getNumber :
def getNumber(tokenList):
if getToken(tokenList, '('):
x = getSum(tokenList) # get the subexpression
getToken(tokenList, ')') # remove the closing parenthesis
return x
else:
]x = tokenList[0
if type(x) != type(0): return None
][ = ]tokenList[0:1
)return Tree (x, None, None
9 * (11 + 5) * 7 :
]'>>> tokenList = [9, '*', '(', 11, '+', 5, ')', '*', 7, 'end
)>>> tree = getSum(tokenList
)>>> printTreePostorder(tree
* * 9 11 5 + 7
.
getNumber .
-6-20
.
.
:
def getNumber(tokenList):
if getToken(tokenList, '('):
)x = getSum(tokenList
if not getToken(tokenList, ')'):
'raise 'BadExpressionError', 'missing parenthesis
return x
else:
# the rest of the function omitted
raise
BadExpressionError . getNumber
264
.
.
raise :3-20
. .
-20-7
.
.
:
5-20 :
265 :
?Can it fly
cat dog
5-20
.
. .
.
.
:
def animal():
# start with a singleton
)"root = Tree("bird
# make a guess
)(guess = tree.getCargo
" ?" prompt = "Is it a " + guess +
if yes(prompt):
"!print "I rule
continue
yes . .
y Y true :
def yes(ques):
from string import lower
))ans = lower(raw_input(ques
)'return (ans[0] == 'y
1 break .
.
while .
) (cargo
.
.
:4-20 .
.
-8-20
) binary tree (
.
267 :
) root(
.
) leaf(
.
) parent (
.
) child(
.
) sibling(
.
) level(
.
) binary operator (
.
preorder
.
prefix
.
postorder
.
inorder
.
268
) subexpression (
.
270
20 . 20
.
.
.
.
.
-1-21
. 1-8
.
.
.
.
. .
.
. ][
. :
">>> String="Python
]>>> print String[3
h
)( ) ( .
:
271 :
-2-21
.
:
]]>>> matrix=[[2,3],[4,5],[6,7
]>>> matrix[2][0
6
][ . .
. :
.
.
. :
][ :
]>>> midterm = mathematics[0
>>> print midterm
5
.
.
:
:
]]>>> student = [[5,11], [3,10
1 0 .
.
100 .
100 .
5
. :
>>>scomputings=s[[[5,11],[3,10]],[[2,7],[3,8]],[[4,7],[3,9]],[[3
]]],9],[2,7]],[[6,12],[5,10
. 4 5
2 .
273 :
.
.
10 100
5 .
10000 .
10000 midterm final
5000 . 500
student ) (student23 5
!
.
.
university . .
:
]'>>>sprintsuniversity[branches['Computing']][students['student2
]]'][lessons['mathematics']][numKind['final
7
!
274
-3-21
.
. 3
5 . 2
.
) ( .
.
.
0 :
def zeroList(n):
][=zl
for inin range(n):
)zl.append(0
return zl
-4-21
.
.
.
.
0 :
for i 0 5 0
. 0
:
275 :
.
:
if .
:
def zeroList(n):
])return [0 for i in range(n
lambda -5-21
.
:
zeroList lambda
.
lambda ) (:
. :
)>>> zeroList(4
][0, 0, 0, 0
:
276
>>> prefix=lambda x,y='Mr.': y+' '+x
)'>>> print prefix('Janson
Mr. Janson
)'>>> print prefix('Janson','Mrs.
Mrs. Janson
reduce
. reduce
. reduce
reduce .
.
.
. reduce .
:
) range(1,-n+1 reduce n .
5 :
4 6 . 24 720 .
. factorial :
def factorial(n):
)return reduce(lambda x, y : x * y, range(1, n+1), 0
.
. 0 1:
)>>> factorial(0
1
277 :
)>>> factorial(-1
1
:1-21 .
-6-21
. 3-21
.
sequence zeroList
0 .
b . 0
:
.
.
zeroList .
.
:
278
def sequence(d):
])zeroList = lambda n:[0 for i in range(n
)]zl = zeroList(d[0
if len(d) == 1:
return zl
else:
for i in range(len(zl)):
)]zl[i] = sequence(n[1:
return zl
-7-21
5-14 .
.
sequence
. sequence .
.
:
)>>> func(2, 3
2
)(3,
func . );(
print .
.
.
279 :
* . print b
3 .
:
)]'>>> func(2,3,{'key':'value'},'string',('tuple',),['list
2
)]'(3, {'key': 'value'}, 'string', ('tuple',), ['list
.
.
)**(
. :
)'>>> func2(2,3,4,5,key='value
2
)(3, 4, 5
}'{'key':'value
.
.
)(a, *b, **c
.
.
. sequence :
def sequence(*n):
])zeroList = lambda x:[0 for I in range(x
)]zl = zeroList(n[0
if len(n) == 1:
return zl
for i in range(len(zl)):
)]zl[i] = sequence(n[1:
return zl
280
. ] zl[i .
sequence *n .
*n
:
def sequence(*n):
from types import TupleType
if type(n[0]) == TupleType:
]n = n[0
])zeroList = lambda x:[0 for i in range(x
)]zl = zeroList(n[0
if len(n) == 1:
return zl
for i in range(len(zl)):
)]zl[i] = sequence(n[1:
return zl
8-5 type
. types
. .
types .
Type
ListType .TupleType
sequence .
:
)>>> sequence(2,3,2
]]][[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0
:
)>>> d = sequence(2,3,2
>>> d[2][1][0] = 123
>>> print d
]]][[[0, 0], [0, 0], [0, 0]], [[0, 0], [123, 0], [0, 0
. .
281 :
.
) ( input raw_input
:
def inputItems(Sequence):
from types import ListType
for i in range(len(Sequence)):
if type(Sequence[i]) != ListType:
)(Sequence[i] = input
else:
)]inputItems(Sequence[i
return Sequence
sequence inputItems
.
lambda .
.
-8-21
.
.
.
15-8 4-10
. . .
.
:
class Matrix:
pass
. sequence
__ __init
282
sequence .
6-21 :
__ __init matrix .
matrix self
Matrix .
dimensions __ __init matrix
. .
. __str__
.
:
def __str__(self):
''=s
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
's+=`self.matrix[i][j]`+'\t
's+='\n
]return s[:-1
s . i j
. ] matrix[i][j .
s.
: )`( =.+
str .
.
.
= +
. + = )
283 :
( . )=* /= = (-
. :
n += x
n = n+x
('\t') tab
)' ('\n .
' '\n
.
print
. :
)>>> m = Matrix(2,3
>>> print m
0 0 0
0 0 0
matrix .
) ( .
inputItems 7-21
.
matrix inputItems .
:
class Matrix:
...
def inputItems(self):
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
while 1:
try:
)'self.matrix[i][j]=input('Item['+`i`+']['+`j`+']:
break
except NameError:
pass
284
__ __str
for ] matrix[i][j
.
input
.
input
. Matrix :
)>>> m = Matrix(2, 3
)(>>> m.inputItems
Element[0][0]:1
Element[0][1]:2
Element[0][2]:3
Element[1][0]:4
Element[1][1]:5
Element[1][2]:6
>>> print m
1 2 3
4 5 6
matrix :
. matrix
:
.
matrix .
-9-21
matrix . .
.
matrix .
)_(
.
.
matrix __matrix
:
class Matrix:
def __init__(self, dimension1=0, dimension2=0):
])zeroList = lambda n:[0 for i in range(n
)self.__matrix = zeroList(dimensoin1
))for i in range(len(self.__matrix
)self.__matrix[i] = zeroList(dimension2
)self.dimensions = (dimension1, dimension2
def __str__(self):
''=s
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
's+=`self.__matrix[i][j]`+'\t
's+='\n
]return s[:-1
def inputItems(self):
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
while 1:
try:
)' self.__matrix[i][j]=input('Item['+`i`+']['+`j`+']:
break
except NameError:
pass
286
:
)>>> m = Matrix(2, 3
>>> print m.__matrix
'AttributeError: Matrix instance has no attribute '__matrix
>>> m._Matrix__matrix
]][[0, 0], [0, 0
)_(
.
.
:2-21
.
.
-10-21
.
.
__ __mul
. __ __mul :
def __mul__(self, other):
)]product = Matrix(self.dimension[0], other.dimensions[1
for i in range(self.dimension[0]):
for k in range(other.dimensions[1]):
for j in range(self.dimensions[1]):
\ * ]product.__matrix[i][k] += (self.__matrix[i][j
)]other.__matrix[j][k
return product
287 :
.
. .
.
.
print :
)>>> m1 = Matrix(3, 1
)(>>> m1.inputItems
Element[0][0] = 1
Element[1][0] = 2
Element[2][0] = 3
)>>> m2 = Matrix(1*2
)(>>> m2.inputItems
Element[0][0] = 4
Element[0][1] = 5
>>> print m1 * m2
4 5
8 10
12 15
-11-21 else
.
lambda
for .
.
288
.
.
6-19 .
.
.
.
.
listOfStrings
. sortedList
. listOfStrings sortedList .
sortedList
. sortedList
. sortedList
:
def sort(listOfStrings):
][ = sortedList
)]sortedList.append(listOfStrings[0
for i in range(1, len(listOfStrings)):
for j in range(len(sortedList)):
if len(listOfStrings[i]) < len(sortedList[j]):
]sortedList[j:j] = listOfStrings[i:i+1
break
if listOfStrings[i] not in sortedList:
)]sortedList.append(listOfStrings[i
return sortedList
for .
sortedList
. .
else .
else
. else
289 :
def sort(listOfStrings):
][ = sortedList
)]sortedList.append(listOfStrings[0
for i in range(1, len(listOfStrings)):
for j in range(len(sortedList)):
if len(listOfStrings[i]) < len(sortedList[j]):
]sortedList[j:j] = listOfStrings[i:i+1
break
else:
)]sortedList.append(listOfStrings[i
return sortedList
.
.
-12-21
) Array(
.
) singel-dimensional sequence (
.
) multi-dimensional sequence (
) ( .
) list comprehension (
.
292
IDLE win32 wxPython Tkinter . ...
.
IDLE PythonWin.
-1- IDLE
IDLE 1.5.2 .
Guido van Rossum
IntegratedaDeveLopmentaEnvironment )
Monty Python ( .
.
IDLE Python Shell Window
File Editor .
. Path Browser
.
Class Browser IDLE .
Find in Files
. IDLE Debug Control Panel
) (.
-1-1- IDLE
IDLE Python 1.5.2
. Tcl/Tk
) . IDLE (.
IDLE Python... Start IDLE
) (Python GUI . idle.pyw . :
C:\program files\PYTHON23\Tools\idle\idle.pyw
293 :
1-
Tcl/Tk Path .
95/98 C:\autoexec.bat Notepad Path
C:\PROGRA~1\Tcl\bin . :
PATH=c:\windows;c:\windows\COMMAND;C:\PROGRA~1\Tcl\bin
-3-1-
IDLE .
.
:
2-
.
. ) console(
.
-4-1-
IDLE .
3- Enter def While
.
.
numa=anuma-a1 . BackSpace
)( . return .
continue break return pass raise )(
.
295 :
3-
-5-1-
Alt + / .
4- divisible .
d Alt + / .
4-
.
Alt + /
. 4- Alt + / not num
numList . nu num numList
.
-6-1-
IDLE
:
296
Enter
.
Alta+aP Alta+aN Enter
. .
) Alta+aP Alta+aN
(
Enter .
-7-1-
.
6-
297 :
.
) (
- .
. 7-
) ( .
:
7-
-8-1-
(File Editor) IDLE
.
:
File > New... Ctrl+N Ctrl+N Ctrl+X
File > Open... Ctrl+O Ctrl+F Ctrl+X
File > Open Modue... Ctrl+M Ctrl+M Ctrl+X
298
New Window )
( . Open
Open Module
. Shelve Shelve.py
) (sys.path .
8-
-1-8-1-
Shell Window
. .
.
Shell Window Tab .
Paste Copy Cut . . . Shell Window .
.
:
299 :
Edit > Indent region ] Ctrl +
Edit > Dendent region [ Ctrl +
Edit > Comment out region Alt + 3
Edit > Uncomment region Alt + 4
Edit > Tabify region Alt + 5 Tab
Edit > Untabify region Alt + 6 Tab
. Tabify region Tab )
Tab ( Untabify region . Tab
.
.
.
-2-8-1-
) ( *
* .
. Save Save as .
) (Save Copy As Save As
.
File > Save Ctrl+S Ctrl+S Ctrl+X Save
-3-8-1-
import
Shell Window ) (Reload.
Import Module File Editor
import reload Shell Window .
-9-1- Find/Replace
Find... Edit 9- :
9-
Wrap around ) Dawn (
) (
301 :
. regularaexpression
.
MatchaCase
WholeaWord
.
Replace... Edit 10- .
Search Dialog
.
10-
11-
PythonWin -2-
PythonWin IDLE
. .
-1-2-
) (Interactive
. Enter
.
) ">>>"
" ( "... . Enter
. Enter .
Enter " "....
.
Undo Edit Undo Ctrl+Z
.
303 :
-2-2-
Save Close Open Print Locate File .
.
sys.path .
Import Import .
PythonWin Import . Reload
Undo Import/Reload Save Open
Print Paste Copy Cut Run Redo . . .
.
306
-1-
:
) (
.
) ( .
print ) (: print .
.
-2-
) (
.
. .
) (
:
)>>> 10 * (1/0
Traceback (most recent call last):
? File "<interactive input>", line 1, in
ZeroDivisionError: integer division or modulo by zero
>>> 4 + Spam*3
Traceback (most recent call last):
? File "<interactive input>", line 1, in
NameError: name 'Spam' is not defined
307 :
>>> '2' + 2
Traceback (most recent call last):
? File "<interactive input>", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects
.
.
NameError ZeroDivisionError .TypeError
.
-
) ( .
) (.
.
.
.
.
-3-
.
:
>>> while 1:
... try:
... ))" x = int(raw_input("Please enter a number:
... break
... except ValueError:
... "print "Oops! That was no valid number. Try again...
...
) Ctrl+C
( .
KeyboardInterrupt .
try :
308
try
except .
try
try .
except
. :
except except
. .
.
:
try:
)'f = open('myfile.txt
)(s = f.readline
))i = int(string.strip(s
except IOError, (errno, strerror):
)print "I/O error(%s): %s" % (errno, strerror
except ValueError:
309 :
tryexcept else
except .
. :
else try
.
tryexcept .
. .
except ) (
.:
>>> try:
... )(spam
... except NameError, x:
... print x
...
name 'spam' is not defined
)(
. try
try
. :
310
>>> def this_fails():
... x = 1/0
...
>>> try:
... )(this_fails
... except ZeroDivisionError, detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero
-4-
raise :
raise
.
raise :
>>> try:
... 'raise NameError, 'Hi there
... except NameError:
... '!print 'An exception flew by
... raise
...
!An exception flew by
Traceback (most recent call last):
? File "<interactive input>", line 2, in
NameError: Hi there
-5- -
. :
311 :
-6-
try
. . :
>>> try:
... raise KeyboardInterrupt
... finally:
... '!print 'Goodbye, world
...
!Goodbye, world
Traceback (most recent call last):
? File "<interactive input>", line 2, in
KeyboardInterrupt
finally try
.
finally .
try break return
finally .
312
finally )
( .
try except finally
.
Downey Allen B., Elkner Jeffrey, Meyers Chris; Wellesley, Massachusetts; April
2002 ; How to Think Like a Computer Scientist: Learning with Python
http://www.python.org
http://www.ibiblio.org/obp/thinkCSpy
http://www.orgmf.com.ar/condor/pyshelf22.zip
http://www.DiveIntoPython.org
http://www.BruceEckle.com