Informatics Rescue Notes
Informatics Rescue Notes
,
7 2012 .
1
1.1 O- . . . . . . . . . . . . . . . . . .
1.1.1 . . . . . . . . . . . . .
1.1.2 . . . . . . . . . . . . .
1.2 . . . . . . . . . . . . . . .
1.3 . . . . . . . . . . . .
1.4 . . . . . . . . . . .
1.5 . . . . . . . . . . . . . . . . . . . .
1.6 . . . . . . . . .
1.7 . . . . . . . . . . . .
1.8 . . . . . . . .
1.9 . . . . . . . . . . .
1.10 - . . . . . . . . . . . . . . . . .
1.10.1 - . . . . .
1.10.2 . . . . . . . .
1.10.3 . . . . . . . . . . . . . .
1.11 . . . . .
1.11.1 . . . . . . . . . .
1.11.2 . . . . . . . . . . . . .
1.11.3 . . . . . .
1.12 C . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
6
6
6
7
7
8
9
10
12
14
16
16
18
18
18
19
20
21
22
24
26
2 Python
2.1
2.1.1 NoneType . . . . . . . . . . . . . . . . . . .
2.1.2 . . . . . . . . . . . . . . . . . . .
2.1.3 . . . . . . . . . . . . . . .
2.1.4 . . . . . . . . . . . . .
2.1.5 . . . . . . . . . . . . . . . . . . . .
2.1.6 . . . . . . . . . . . . . . . . . .
2.2 . . . . . . . . . . . . . . . . . . . . . .
2.3 . . . . . . . . . . . . . . . . . . . . . . .
2.4 . . . . . . .
2.4.1 . . . . . . . . .
2.4.2 . . . . . . . . . . . . . . . . . . .
2.4.3 . . . . . . . . . . . . . . . . . .
2.4.4 . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
28
29
29
29
30
34
40
43
45
49
52
52
54
54
55
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
55
56
58
59
62
64
65
66
66
67
68
72
72
75
78
3
3.1 . . . . . . . . . .
3.1.1 . . . . . . . . .
3.1.2 . . . . . . . . . . . . .
3.2 . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2.1 . . . . . . . . . . . . . . . . . . .
3.2.2 : . . . . . . . . . .
3.2.3 :
3.2.4 . . . . . . . . . . . . . . . . . . . .
3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.3.1 . . . . . . . . . . . . . . . . . . . . . .
3.3.2 . . . . . . . . . . . . . . . . . . .
3.3.3 . . . . . . . . . . . . . . . .
3.3.4 . . . . . . . . . . . . . . . .
3.3.5 . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
81
81
81
83
84
84
85
88
93
93
93
93
93
93
93
4
4.1 TCP . . . . . . . . . . . . . . . . . . . . . . .
4.1.1 . . . . . . . . . . . .
4.1.2 TCP . . . . . . . . . . . . . . . . . .
4.1.3 TCP . . . . . . . . . .
4.1.4 TCP . . . . . . . . . . .
4.1.5 TIME_WAIT . . . . . . . . . . . . .
4.2 UDP . . . . . . . . . . . . . . . . . . . . . . .
4.2.1 UDP TCP . . . . . .
4.3 POSIX API . . . . . . . . . . . . . . . . . .
4.3.1 DAYTIME . . . . . . . . .
4.3.2 DAYTIME ,
4.3.3 DAYTIME . . . . . .
4.3.4 / . . . . . .
4.3.5 .
4.4 . . . . . . . . . . . . .
4.4.1 . . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
94
94
94
95
95
96
96
98
98
98
98
102
104
107
111
117
118
2.5
2.6
2.7
2.8
2.9
2.10
2.11
2.12
2.13
2.4.5 . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
2.6.1 . . . . . . . . . .
-
2.7.1 . . . . . . . . . . . . . . . . . .
2.7.2 MRO . . . . . . . .
2.7.3 . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
2.10.1 . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
2
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
119
120
120
121
121
122
124
124
127
127
127
127
128
5
5.1 - . . . . . . . . . . . . . . . . . . . .
5.1.1 . . . . . . . . . . . . . . . . . . . . . . .
5.2 . . . . . . . . . . . . . . . . . . . . .
5.2.1 . . . . . . . . . . . . . . . . . . . . . . .
5.3 . . . . . . . . . . . . . . . . . . . . . . . . .
5.3.1
5.3.2 . . . . . . . . . . . . . . . . . . . . . . .
5.4 B- . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.4.1 B- . . . . . . . . . . . . . . .
5.4.2 . . . . . . . . . . . . . . . . . . . . . . .
5.5 . . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
132
132
132
134
134
136
136
137
138
138
139
140
6 Common Lisp
6.1 . . . . . . . . . . . . . . . . . . . . . . .
6.1.1 . . . . . . . . . . . .
6.1.2 . . . . . . .
6.1.3 . . . . . . . . .
6.1.4 . . . . . . . . . . . .
6.2 . . . . . . . . . . . . . . . . . . . . .
6.2.1 . .
6.2.2 ()
6.2.3 . . . . . . . . . . . . . . . . . .
6.2.4 . . . . . . . . . . . . . . . .
6.3 . . . . . . . . . . . . . . . . . . . . . . .
6.3.1 . . . . . . . . . . . . . .
6.3.2 . . . . . . . . . . . . . . . . . .
6.3.3 . . . . . . . . . . . .
6.3.4 . . . . . . . . . . . . .
6.4 . . . . . . . . . . . .
6.4.1 . . . . . . . . . . . . . . . . . . . . .
6.4.2 . . . . . . . . . . . . . . . . . . . . .
6.4.3 . . . . . . . . . . . . . . . . . . . .
6.5 . . . . . . . . . . . . . . . . . . . . . .
6.5.1 . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
144
144
145
147
147
148
148
149
149
150
150
151
152
152
153
154
154
154
156
156
156
157
4.5
4.6
4.4.2 . . . . . . . . . . . . . . . . . . . . . .
4.4.3 . . . . . . . . . . . . . . . . . . . . .
4.4.4
4.4.5 NAT . . . . . . . . . . . . . .
4.4.6 ARP . . . . . . . . . . . . . . . . . . . . . . . .
4.4.7 ICMP . . . . . . . . . . . . . . . . . . . . . . .
4.4.8 DHCP . . . . . . . . . . . . . . . . . . . . . . .
4.4.9 DNS . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
4.5.1 - . . . . . . . . . . . . .
4.5.2 . . . . . . . . . . . . . . . .
4.5.3 . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
6.6
6.7
6.8
6.9
6.10
6.11
6.12
6.13
6.5.2 . . . . .
6.5.3 - . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
6.6.1 Cons- . . . . . . . . . . . . . . . . . .
6.6.2 . . . . . . . . . . . . .
6.6.3 . . . . . . . . . . . . . . . . . .
6.6.4 . . . . . . . . . . . . . .
6.6.5 . . . . . . . . . . . .
6.6.6 . . . . . . . . . . . .
6.6.7 Destructuring-bind . . . . . . . . . . . . . . .
Loop . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.7.1 . . . . . . . .
6.7.2 . . . . . . . . . . . . . .
Format . . . . . . . . . . . . . . . . . . . .
6.8.1 . . . . . . . . . . . . . . . . . . .
6.8.2 . . . . . . . . . .
6.8.3 . . . . . . . . . . . . . . . . . . . .
6.8.4 . . . . . . . .
CLOS . . . . . . . . . . . . . . . . . . . . . . . . . .
6.9.1 . . . . . .
6.9.2 . . . . . . . . . .
6.9.3 . . . . . . . . . . . . . . . . . . . . .
6.9.4 . . . . . . . . . . . . . .
6.9.5 . . . . . . . . . . .
6.9.6 . . . . . . . . . . . . . . .
6.9.7 . . . . . . . . . . . . . . . . . .
6.9.8 . . . . . . . . . . . .
6.9.9 . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
6.10.1 . . . . . . . . . . . . . . . .
6.10.2 . . . . . . . . . . . .
6.10.3 . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
6.11.1 . . . . . . . . . . . . .
:
6.12.1 . . . . . . . . . . . . .
6.12.2 . . . . . . . . . . . . . . . . . . .
6.12.3 . . . . . . . .
6.12.4 . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
7
7.1 . . . . . . . . . . . . . . . .
7.1.1 . . . . . . . . .
7.2 . . . . . . . . . . . . . . . . . . .
7.2.1 k . . . . . . . . . . .
7.2.2 . . . . . . . . . . . . . . . . . .
7.2.3 k . . . .
7.2.4 :
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
157
159
160
160
160
161
162
163
163
164
164
165
168
171
171
173
174
174
174
174
176
179
179
179
181
182
182
183
183
183
184
184
185
186
186
186
187
188
189
189
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
194
194
195
197
197
198
200
201
7.3
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7.3.1 k . . . . . . . . . . . . . . . . . . . . . . . . . 201
7.3.2 kd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
1.1
O-
.
. .
, .
an2 + bn + c, a, b c .
n ,
n2 . ,
(n2 ).
, .
1.1.1
f (n) O(g(n))
f g ( )
f g ( )
f g
g f
f g
f (n) (g(n))
f (n) (g(n))
f (n) o(g(n))
f (n) (g(n))
1.
1.1.2
f (n) O(g(n))
= c > 0, n0
n > n0
f (n) c g(n),
(1.1)
f (n) (g(n))
= c > 0, n0
n > n0
c g(n) f (n),
(1.2)
f (n) (g(n))
= c1 > 0, c2 > 0, n0
f (n) o(g(n))
= > 0 n0
n > n0
(1.4)
f (n) (g(n))
= c > 0 n0
n > n0
(1.5)
n > n0
1.2
(1.3)
.
log n.
:
, .
, .
:
, , ,
.
, , , .
Listing 1.1:
1
11
16
1.
Listing 1.2:
12
return mid ;
}
17
1.3
quicksort. :
;
:
1. , ;
2. , ;
.
(n2 )
(n log n)
(n log n)
,
, .
Listing 1.3:
1.
int i , last = 0;
if ( n <= 1)
return ;
14
swap (a , 0 , rand () % n ) ;
for ( i = 1; i < n ; i ++)
if ( a [ i ] < a [0])
swap (a , ++ last , i ) ;
swap (a , 0 , last ) ;
19
quicksort (a , last ) ;
quicksort ( a + last + 1 , n - last - 1) ;
}
1.4
, .
n-
(1)
(n)
(1)
(n)
. (n),
n . n1 , ,
1 .
Listing 1.4:
12
17
22
struct ea {
int count ;
int max ;
int * a ;
};
enum {
EA_INIT = 1 ,
EA_GROW = 2
};
int add ( struct ea * ea , int value )
{
if ( NULL == ea - > a ) {
ea - > a = ( int *) malloc ( EA_INIT * sizeof ( int ) ) ;
if ( NULL == ea - > a )
return -1;
ea - > max = EA_INIT ;
ea - > count = 0;
} else if ( ea - > count == ea - > max ) {
int * a = ( int *) malloc ( EA_GROW * ea - > max * sizeof ( int ) ) ;
if ( NULL == a )
(amortized analysis).
1.
10
return -1;
memcpy (a , ea - >a , ea - > count * sizeof ( int ) ) ;
free ( ea - > a ) ;
27
42
47
return 0;
}
Listing 1.5:
1
11
struct ea array ;
( void )
( void )
( void )
( void )
( void )
5) ;
3) ;
2) ;
7) ;
6) ;
16
1.5
. . , - ;
.
1.
11
n-
(n)
(n)
(1)
.
Listing 1.6:
struct list {
int data ;
struct list * next ;
};
struct list * make_item ( int data )
{
struct list * item = ( struct list *) malloc ( sizeof ( struct list ) ) ;
item - > data = data ;
item - > next = NULL ;
12
return item ;
}
17
22
27
}
# define for_each (n , head )
for ( n = ( head ) ; n != NULL ; n = n - > next )
37
42
\
\
47
free ( current ) ;
return head ;
}
1.
12
prev = current ;
52
}
return head ;
}
57
62
67
72
Listing 1.7:
struct list * head = NULL ;
2
12
head
head
head
head
head
=
=
=
=
=
17
1.6
. 0..2 . , ,
. .
, :
1. .
2. .
1.
13
3. .
(log n)
(n)
(log n)
(n)
(n)
(n)
, 1..10, .
Listing 1.8:
struct tree {
int data ;
struct tree * left ;
struct tree * right ;
};
struct tree * make_node ( int data )
{
struct tree * node = ( struct tree *) malloc ( sizeof ( struct tree ) ) ;
node - > data = data ;
node - > left = NULL ;
node - > right = NULL ;
14
return node ;
}
19
24
return root ;
29
34
39
44
1.
14
{
a p p l y _ f n _ p r e o r d e r ( root , & print_node ) ;
49
Listing 1.9:
1
=
=
=
=
=
insert ( root ,
insert ( root ,
insert ( root ,
insert ( root ,
insert ( root ,
make_node (8) ) ;
make_node (3) ) ;
make_node (1) ) ;
make_node (6) ) ;
make_node (10) ) ;
print_tree ( root ) ;
1.7
, :
2 .
d 1, d.
.
.
max
max
(1)
(log n)
(log n)
.
, .
( , ). ,
, . , , ,
, .
Listing 1.10:
1
# define HEAP_SIZE 50
struct binheap {
int data [ HEAP_SIZE ];
int size ;
};
static inline int topos ( int i )
2 , , , ,
.
1.
{
return i + 1;
11
16
21
26
31
36
41
46
if ( l < heap - > size && heap - > data [ l ] > heap - > data [ i ])
largest = l ;
if ( r < heap - > size && heap - > data [ r ] > heap - > data [ largest ])
largest = r ;
51
if ( largest != i ) {
swap ( heap - > data , i , largest ) ;
max_heapify ( heap , largest ) ;
}
}
56
Listing 1.11:
1
int i ;
struct binheap heap = {
15
1.
16
. data = { 9 , 1 , 11 , 13 , 7 , 3 , 15 , 17 , 5 } ,
. size = 9
};
6
1.8
heapsort. :
in-place.
() . [1..(n 1)]
. .
(n log n)
(n), O(n log n)
(n log n)
Listing 1.12:
1
11
1.9
, :
Insert(S, x) x S;
M aximum(S) ;
ExtractM ax(S) , S;
IncreaseKey(S, x, k) x k, .
1.
17
. .
heap_maximum , , .
heap_extract_max , heap_maximum, . :
.
.
max_heapif y.
heap_increase_key , . :
.
,
.
heap_insert k .
:
.
heap_increase_key k.
Listing 1.13:
12
return max ;
}
17
27
1.
18
}
32
37
Listing 1.14:
13
int i ;
struct binheap heap = {
. data = { 9 , 1 , 11 , 13 , 7 , 3 , 15 , 17 , 5 } ,
. size = 9
};
bui ld_max _heap (& heap ) ;
heap_insert (& heap , 8) ;
heap_insert (& heap , 19) ;
( void ) h e a p _ e x t r a c t _ m a x (& heap ) ;
( void ) h e a p _ i n c r e a s e _ k e y (& heap , 6 , 12) ;
for ( i = 0; i < heap . size ; i ++)
printf ( " % d " , heap . data [ i ]) ;
1.10
,
. -.
- .
.
O(1)
(n)
O(1)
(n)
1.10.1
- () .
. k
k m, . h(k) = k mod m.
- m. , m = 2p , h(k) p k.
- .
. h(k) = bm(kA mod 1)c, 0 < A < 1.
m.
51
1
A = 2 0.6180339887...
1.10.2
. - . , , .
1.
19
. -.
, .
, - ;
,
- .
.
-, [0.7; 0.75],
-, > 0.75 ( , ).
:
0
1.10.3
- m.
.
Listing 1.15:
12
# define HTABLE_SIZE
# define MULTIPLIER
20
31
struct item {
char * name ;
int value ;
struct item * next ;
};
struct item * make_item ( char * name , int value )
{
struct item * item = ( struct item *) malloc ( sizeof ( struct item ) ) ;
item - > name = name ;
item - > value = value ;
item - > next = NULL ;
17
return item ;
}
22
1.
20
for (; * p != \0 ; p ++)
h = MULTIPLIER * h + * p ;
return h % HTABLE_SIZE ;
27
32
struct item * lookup ( struct item * htable [] , char * name , bool create , int value
)
{
int h = hash ( name ) ;
struct item * i = htable [ h ];
for (; i != NULL ; i = i - > next )
if ( strcmp ( name , i - > name ) == 0)
return i ;
37
if ( create ) {
i = make_item ( name , value ) ;
i - > next = htable [ h ];
htable [ h ] = i ;
}
return i ;
42
}
Listing 1.16:
struct item * htable [ HTABLE_SIZE ] = { NULL };
14
char * strings [] = { " string1 " , " string2 " , " string3 " ,
" string4 " , " string5 " };
int i ;
struct item * it ;
for ( i = 0; i < 3; i ++)
lookup ( htable , strings [ i ] , true , i + 1) ;
for ( i = 0; i < 5; i ++) {
it = lookup ( htable , strings [ i ] , false , 0) ;
if ( it )
printf ( " % s in hash table , value = % d \ n " , it - > name , it - > value ) ;
else
printf ( " % s somewhere else \ n " , strings [ i ]) ;
}
1.11
, ee
ee , , , , .
.
:
1. .
2. , .
3. ,
.
1.
21
4. , .
1.11.1
,
.
Fn :
n = 0
0
1
n = 1
Fn =
Fn1 + Fn2
. F5 :
F5 = F4 + F3
= F3 + F2 + F2 + F1
= F2 + F1 + F1 + F0 + F1 + F0 + 1
= F1 + F0 + 1 + 1 + 0 + 1 + 0 + 1
=1+0+1+1+0+1+0+1
= 5,
, F5 , F4 1 , F3 2 , F2 3
, F1 5 , F0 3 .
Listing 1.17:
F100 ,
.
(n),
(n) . t,
ti = ti1 + ti2 , 2 i n.
Listing 1.18:
unsigned long fib_fast ( unsigned long n )
{
unsigned long t [ n + 1];
4
if ( n <= 1)
return n ;
t [0] = 0;
t [1] = 1;
1.
22
(n) , ,
Fi Fi1 Fi2 .
Listing 1.19:
1
11
return t [1];
16
1.11.2
K = {k0 , k1 , ..., kk }, ki N, k0 = 1 .
. : k0 = 1 ., k1 = 5 ., k2 = 10
., k3 = 25 .
, K , kk > kk1 > ... > k0 .
.
,
n .
. Ci,j k0 , k1 , ..., ki , j. Ci,j
:
1. , ki ( ),
Ci,j = Ci1,j .
2. ki
,
Ci,j = 1 + Ci,jki .
Ci,j = min(Ci1,j , 1 + Ci,jki ).
1.
23
.
, , j j 1 .:
j < 0
0
j = 0
Ci,j =
i = 0
j
min(Ci1,j , 1 + Ci,jki )
j 1
.
Ci,j , .
# define array_size ( a )
( sizeof ( a ) / sizeof (( a ) [0]) )
\
\
# define min (a , b )
({ __typeof__ ( a ) _a = ( a ) ;
__typeof__ ( b ) _b = ( b ) ;
_a < _b ? _a : _b ; })
\
\
\
14
19
24
solution[k - 1][n] ,
.
. Ck,n ,
.
void recover_coins ( unsigned int n , unsigned int k , unsigned int coins [ k ] ,
unsigned int solution [ k ][ n + 1] , unsigned int counts [ k ])
{
unsigned int i , j ;
5
10
i = k - 1;
j = n;
while ( true ) {
if (0 == j )
break ;
1.
15
if (0 == i ) {
counts [0] += j ;
break ;
}
20
25
24
}
}
Listing 1.20:
13
18
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
int
int
int
int
int
int
i, j;
n = 8;
coins [] = { 1 , 4 , 6 };
k = array_size ( coins ) ;
solution [ k ][ n + 1];
counts [ k ];
23
1.11.3
, ,
, , .
. S1 S2 m n . d(m, n).
d(i, j) i 0 m j 0 n.
d(i, 0) = i
d(0, j) = j,
, S1 [1..i] , i .
S2 [1..j] .
1.
25
. d(i, j) . , ,
( S1 [i] = S2 [j]).
, S2 (j) .
, ( ), Si [1..i]
S2 [1..j 1], . , d(i, j) = d(i, j 1) + 1.
: , S1 [i].
S1 [1..i 1] S2 [1..j]. d(i, j) = d(i 1, j) + 1.
, S1 [i] S2 [j]. S1 [1..i 1] S2 [1..j 1], .
: d(i, j) = d(i 1, j 1) + 1 .
S1 [i] = S2 [j], , d(i, j) = d(i 1, j 1),
S1 [1..i] S2 [1..j] S1 [1..i 1] S2 [1..j 1].
. , d(i, j) :
0
i = 0, j = 0
i
i > 0, j = 0
j
i = 0, j > 0
min(
,
d(i, j) =
d(i, j 1) + 1,
d(i 1, j) + 1,
d(i
1, j 1) + t(S1 [i], S2 [j])
)
i > 0, j > 0
t(a, b) a = b, .
. . distances[m][n] .
# define min (a , b )
({ __typeof__ ( a ) _a = ( a ) ;
__typeof__ ( b ) _b = ( b ) ;
_a < _b ? _a : _b ; })
\
\
\
10
15
20
1.
change += distances [( i - 1) * n + ( j - 1) ];
distances [ i * n + j ] = min ( min ( add , del ) , change ) ;
25
}
}
Listing 1.21:
13
1.12
right-left.
2["abc"]. , ?
. # ##.
26
[1] . , . , . , . , : . , 2- ., 2005.
[2] . , , . .: ; -, 2003.
[3] . , . , . , 2005.
[4] . , . , . , 5- ., 2009.
[5] . , Linux. , 2- ., 2008.
[6] . , . , . , 2- ., 2008.
[7] . , : . , 2006.
[8] . , . . , 3- ., 2007.
27
Python
Python, REPL ( Read, Eval, Print, Loop),
python ( ipython). Python,
.
.
Listing 2.1:
% ipython
Python 2.7.2 ( default , Jun 29 2011 , 15:07:32)
Type " copyright " , " credits " or " license " for more information .
5
10
In [1]: 2 ** 32
Out [1]: 4294967296
15
20
25
30
28
2. PYTHON
2.1
29
Python . , . , . Python
. . - , , , TypeError
AttributeError.
. ,
.
(mutable immutable ).
2.1.1
NoneType
None. , , , . None
1 ..
2.1.2
False , True .
( !)
if while. :
None;
False;
;
;
();
, , __nonzero__
() __len__() , False .
class Zero ( object ) :
def __nonzero__ ( self ) :
return False
5
10
15
2. PYTHON
30
.
x or y. x , x, y. , .
>>> 0 or 2 or 1 or 0
2
x and y. x , , y
. y,
.
>>> 1 and 2 and 0 and 3
0
not x.
2.1.3
x. , False, .
, int, long, float
complex.
2. PYTHON
31
: +x, -x, ~x. + . - .
~ , -(x + 1).
>>> x = 111
>>> + x
111
>>> -x
-111
>>> bin ( x )
0 b1101111
>>> bin (~ x )
-0 b1110000
: x + y, x - y, x * y, x // y, x / y, x % y, x ** y. . / //
. ,
/ 3 . // b x
y c. %
; . ** x
y.
:
int, long.
10
15
>>> 7 + 5
12
>>> 7 - 5
2
>>> 7 * 5
35
>>> 7 / 5
1
>>> 7.0 / 5
1.4
>>> 7.0 // 5
1.0
>>> 7 % 5
2
>>> 3.14 % 0.7
0.3400000000000003
>>> 2**100
1267650600228229401496703205376 L
2. PYTHON
32
Python 4 .
,
.
1
11
16
21
class Id e nt it y El em e nt ( object ) :
def __repr__ ( self ) :
return " Id e nt it y El em e nt "
def __str__ ( self ) :
return self . __repr__ ()
def __add__ ( self , other ) :
return other
def __radd__ ( self , other ) :
return other
def __mul__ ( self , other ) :
return other
def __rmul__ ( self , other ) :
return other
>>> identity = Id en t it yE l em ent ()
>>> identity
I de nt i ty E le me n t
>>> 5 + identity
5
>>> identity * 5
5
Python ,
, , .
math , , , , ..
, ,
cmath.
random , , . .
>>> random . random ()
0.37444887175646646
>>> random . uniform (1 , 10)
1.1800146073117523
4 http://docs.python.org/reference/datamodel.html#special-method-names
, .
2. PYTHON
5
33
10
>>>
>>>
>>>
[7 ,
items = [1 , 2 , 3 , 4 , 5 , 6 , 7]
random . shuffle ( items )
items
3 , 2 , 5 , 6 , 4 , 1]
15
3)
fraction .
10
15
decimal (decimal
floating point numbers).
:
.
, 1.2
, .
>>> 1.1 + 2.2
3.3000000000000003
. 0.1 +
0.1 + 0.1 0.3 0, :
>>> 0.1 + 0.1 + 0.1 - 0.3
5 . 5 5 1 1 1 5 1 2 3 1 2 5 7 8 3 e -17
(precision).
decimal:
2. PYTHON
10
15
34
2.1.4
(mutable) (immutable). :
x in s. , s x;
. , x s.
>>> 2 in [1 , 2 , 3]
True
>>> boo in boozers
True
x not in s.
, . , x
s.
>>> 4 not in [1 , 2 , 3]
True
s + t.
s t.
5 , , .
2. PYTHON
35
>>> (1 , 2 , 3) + (4 , 5)
(1 , 2 , 3 , 4 , 5)
>>> foo + bar
foobar
s * n n * s. n . n <= 0,
. , shallow 6
.
10
>>>
[]
>>>
[]
>>>
[1 ,
[1 , 2 , 3] * -1
[1 , 2 , 3] * 0
[1 , 2 , 3] * 2
2 , 3 , 1 , 2 , 3]
s[i]. i- s. 0.
, . -1.
s[i:j]. , ,
i j. . i,
; j, .
s[i:j:k]. , k.
>>>
>>>
[3 ,
>>>
[3 ,
>>>
[3 ,
>>>
[0 ,
len(s).
s = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
s [3: -1]
4 , 5 , 6 , 7 , 8]
s [3:]
4 , 5 , 6 , 7 , 8 , 9]
s [3: -1:2]
5 , 7]
s [:]
1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
s.
max(s). -
s.
6 shallow deep. ,
, .
2. PYTHON
36
>>> s = [4 , 1 , 9 , 5 , 6]
>>> min ( s )
1
>>> max ( s )
9
, Python bytearray.
s[i] = x. i- x.
>>>
>>>
>>>
[1 ,
s = [1 , 2 , 3]
s [1] = 4
s
4 , 3]
s[i:j] = t.
>>>
>>>
>>>
[2 ,
t.
s = [1 , 2 , 7 , 8]
s [:2] = [2 , 3]
s
3 , 7 , 8]
>>> s [2:2] = [4 , 5 , 6]
[2 , 3 , 4 , 5 , 6 , 7 , 8]
10
>>> s [1:6] = []
[2 , 8]
s[i:j:k] = t. , ,
.
>>>
>>>
>>>
[1 ,
s = [1 , 1 , 3 , 3]
s [1::2] = [2 , 4]
s
2 , 3 , 4]
del s[i:j]
>>>
>>>
>>>
[1 ,
del s[i:j:k]. s.
s = [1 , 2 , 3 , 4 , 5]
del s [ -1]
s
2 , 3 , 4]
2. PYTHON
s.append(x).
>>>
>>>
>>>
[1 ,
37
x s.
s = [1 , 2]
s . append (3)
s
2 , 3]
s.extend(t).
s.
>>>
>>>
>>>
[1 ,
s = [1 , 2]
s . extend ([3 , 4])
s
2 , 3 , 4]
s.insert(i, x).
>>>
>>>
>>>
[0 ,
x i.
s = [1 , 2]
s . insert (0 , 0)
s
1 , 2]
s.pop([i]). i .
, .
>>>
>>>
4
>>>
[1 ,
>>>
2
>>>
[1 ,
s = [1 , 2 , 3 , 4]
s . pop ()
s
2 , 3]
s . pop (1)
s
3]
s.remove(x).
x.
>>>
>>>
>>>
[1 ,
s = [1 , 3 , 2 , 3 , 4]
s . remove (3)
s
2 , 3 , 4]
s.reverse().
>>>
>>>
>>>
[3 ,
in-place.
s = [1 , 2 , 3]
s . reverse ()
s
2 , 1]
2. PYTHON
38
>>> s = [ C , d , E , A , b , f ]
>>> s . sort ( key = lambda x : x . lower () )
>>> s
[ A , b , C , d , E , f ]
10
>>> s = [ C , d , E , A , b , f ]
>>> s . sort ( key = lambda x : x . lower () , reverse = True )
>>> s
[ f , E , d , C , b , A ]
.
. :
string "string".
, .
string """string""". .
.
>>> This
... makes
... sense .
This \ nmakes \ nsense .
:
r R.
7 . , , .
>>> print one \ ntwo
one two
>>> print r one \ ntwo
one \ ntwo
u U. 8 .
Python % format(*args, **kwargs)9 .
, . . PEP 3101 10 . ,
:
>>> My name is {0[ name ]} . format ( dict ( name = Fred ) )
My name is Fred
7 http://docs.python.org/reference/lexical_
analysis.html#string-literals
8 Python 3.x ; unicode ,
str , unicode 2.x.
9 3.x format,
.
10 http://www.python.org/dev/peps/pep-3101/
2. PYTHON
10
39
s.upper(). -
.
>>> FOObar . lower ()
foobar
s.split([sep[, maxsplit]]). sep . sep , , ,
.
maxsplit.
>>> 1 ,2 ,3 . split ( , )
[ 1 , 2 , 3 ]
>>> 1 , ,3 . split ( , )
[ 1 , , 3 ]
>>> 1 2 3 . split ()
[ 1 , 2 , 3 ]
>>> 1 2 3 . split ( None , 1)
[ 1 , 2 3 ]
s.join(iterable).
, iterable,
s.
>>> , . join ( str ( i ) for i in xrange (10) )
0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9
2. PYTHON
40
Python . . ;
. ,
(1), , (n).
. , , . :
(packing) , (unpacking):
1
>>> t = 1 , 2 , 3
>>> a , b , c = t
>>> b
2
2.1.5
. . :
:
1
:
2
, 2, , .
2
(dict comprehension)11 .
2
11
Python 2.7. , .
2. PYTHON
41
, ,
, (,
). ,
, . :
2
12
>>> d = dict ()
>>> d [ list () ] = 1
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
TypeError : unhashable type : list
>>> class dummy ( object ) :
...
def __init__ ( self ) :
...
self . _list = list ()
...
>>> d [ dummy () ] = 1
>>> d
{ < __main__ . dummy object at 0 x7f922fb3a410 >: 1}
:
d[key]. , key. KeyError.
>>> d = dict ( one =1)
>>> d [ one ]
1
d[key] = value.
value key.
>>> d = dict ()
>>> d [ fruits ] = ( banana , apple , pear )
>>> d
{ fruits : ( banana , apple , pear ) }
del d[key].
, key.
d.
d.clear().
2. PYTHON
5
10
42
>>> d . iteritems ()
< dictionary - itemiterator object at 0 x7f922fb88f18 >
>>> for k , v in d . iteritems () :
...
print k , : , v
...
two : 2
one : 1
10
()
>>> d . keys ()
[ two , one ]
>>> d . iterkeys ()
< dictionary - keyiterator object at 0 x7f922fb88f18 >
>>> for k in d . iterkeys () :
...
print k ,
...
two one
10
>>> d . values ()
[2 , 1]
>>> d . itervalues ()
< dictionary - valueiterator object at 0 x7f922fb88f18 >
>>> for v in d . itervalues () :
...
print v ,
...
2 1
d.update(other).
other.
2. PYTHON
2.1.6
43
(set) Python ,
. .
: set frozenset. set , frozenset .
:
set() frozenset().
>>> basket = [ apple , orange , apple , pear , orange , banana ]
>>> fruits = set ( basket )
>>> fruits
set ([ apple , banana , orange , pear ])
:
1
(set comprehension)12 .
: , , . . , ,
:
len(s). s.
>>> s = set ([1 , 2 , 3])
>>> len ( s )
3
x in s
x not in s. , x -
s.
s.isdisjoint(other). , s
other, s other .
>>> s1 , s2 , s3 = set ([1 , 2 , 3]) , set ([4 , 5 , 6]) , set ([3 , 4])
>>> s1 . isdisjoint ( s2 )
True
>>> s1 . isdisjoint ( s3 )
False
s.issubset(other)
, s other, s != other.
Python 2.7. , .
2. PYTHON
44
, other s, other != s.
s | other. , -
.
>>> s1 , s2 = set ([1 , 2]) , set ([2 , 3])
>>> s1 . union ( s2 )
set ([1 , 2 , 3])
s.intersection(other)
s & other. .
s - other. .
s ^ other. .
:
s.add(x). x s.
>>> s = set ([1 , 2])
>>> s . add (3)
>>> s
set ([1 , 2 , 3])
s.remove(x).
KeyError.
x . ,
x , .
s.clear().
2. PYTHON
45
2.2
if
if 13 :
if expression: suite
( elif expression: suite) *
[ else : suite ]
expression ,
True. suite. , else ,
.
, ,
, - .
import os . path
:
1
while
while :
while expression: suite1
[ else : suite2 ]
2. PYTHON
5
10
46
...
print suite -2
...
suite -1: 1
suite -1: 2
suite -1: 3
suite -2
break else.
continue .
for
for :
for variable in expression: suite1
[ else : suite2 ]
expression . . suite1 , ,
variable .
else.
break else.
continue ,
, else.
try
try :
2. PYTHON
47
try : suite1
( except [ expression [ ( as | , ) target ] ]: suite2 ) +
[ else : suite3 ]
[ finally : suite4 ]
try : suite1
finally : suite4
except .
suite1 , .
>>> try :
...
print Hello .
... except Ar i th me t ic E rr or :
...
print Arithmetic error occured .
... except :
...
print Error occured .
...
Hello .
>>> try :
...
1 / 0
... except Z e r o D i v i s i o n E r r o r :
...
print Illegal operation performed .
...
Illegal operation performed .
, ArithmeticError, ZeroDivisionError.
>>> try :
...
1 / 0
... except Ar i th me t ic E rr or :
...
print Here we catch all arithmetic errors .
...
Here we catch all arithmetic errors .
except expression, , . ,
.
>>> try :
...
x
... except Ar i th me t ic E rr or :
...
print Here we catch all arithmetic errors .
... except :
...
print Here we are catching even NameError .
...
Here we are catching even NameError .
,
, finally . ,
, . , try
NameError, finally Exception.
2. PYTHON
48
>>> try :
...
x
... finally :
...
raise Exception
...
Traceback ( most recent call last ) :
File " < stdin > " , line 4 , in < module >
Exception
expression , ,
.
except , target, ,
expression, . ,
, try.
>>> try :
...
1 / 0
... except Exception , e :
...
print e
...
integer division or modulo by zero
>>>
...
...
...
...
...
...
2
Sum
try :
1 + 1
except :
print Error occured .
else :
print Sum done well .
done well .
>>> try :
...
raise Exception
... finally :
...
print in finally
...
in finally
Traceback ( most recent call last ) :
File " < stdin > " , line 2 , in < module >
Exception
sys.exc_info(), (
exc_type, exc_value, exc_traceback), exc_type , exc_value ,
, exc_traceback traceback .
traceback.
Python Python:
import sys
import traceback
2. PYTHON
10
15
49
14
>>> 1 / 0
Exception in user code :
-----------------------------------------------------------Traceback ( most recent call last ) :
File " test . py " , line 7 , in run_user_code
exec source in envdir
File " < string > " , line 1 , in < module >
Z e r o D i v i s i o n E r r o r : integer division or modulo by zero
----------------------------------------------------------->>> Traceback ( most recent call last ) :
File " test . py " , line 16 , in < module >
run_user_code ( envdir )
File " test . py " , line 5 , in run_user_code
source = raw_input ( " >>> " )
EOFError
with
with :
with expression [ as target ]: suite
:
1. expression .
2. __enter__() expression.
3. as target, __enter__ target.
4. suite.
5. __exit__(). suite
__exit__() False, .
import threading
lock = threading . Lock ()
with lock : ...
2.3
2. PYTHON
1
50
def add (a , b ) :
return a + b
, def,
, , . return. , , None.
(
) .
, .
14 . ,
.
, .
,
.
.
retries -= 1
if retries < 0:
raise IOError ( User has not approved or declined an action . )
print complaint
14
:
1
.
. (mutable) ,
, :
def append ( list =[]) :
list . append ( a )
return list
14
. 58.
2. PYTHON
5
10
51
>>> append ()
[ a ]
>>> append ()
[ a , a ]
>>> append ()
[ a , a , a ]
, :
10
*identifier, identifier
, , .
**identifier, identifier ,
.
def fargs (* args ) :
print args
10
,
, TypeError. *
identifier, identifier ,
.
**identifier, identifier , ,
.
def fargs (a , b , c ) :
print a , b , c
10
>>> kwargs = { a : 2 , b : 3 , c : 4 }
>>> fkwargs (** kwargs )
2 3 4
,
.
2. PYTHON
52
(docstring), . __doc__.
def func () :
""" Here goes docstring . """
pass
5
() Python ,
. -:
lambda [ parameters ]: expression
-
(statements).
>>> map ( lambda i : i + 1 , [1 , 2 , 3])
[2 , 3 , 4]
2.4
Python .
2.4.1
,
. , .
def compose (g , f ) :
return lambda x : g ( f ( x ) )
3
def f ( x ) :
return x + 3
def g ( x ) :
return 2 * x
>>> z = compose (g , f )
>>> z (2)
10
, Python.
map
map ,
.
.
2. PYTHON
53
, None. . None,
, ;
, .
map ( function , sequence [ , sequence , ...]) -> list
filter
filter , , . ,
, . None, , .
filter ( function or None , sequence ) -> list , tuple , or string
>>> filter ( lambda x : x % 2 , [1 , 2 , 3 , 4 , 5])
[1 , 3 , 5]
reduce
reduce , , , , . : function, initial sequence.
reduce ( function , sequence [ , initial ]) -> value
4! , reduce:
>>> reduce ( lambda res , x : res * x , [2 , 3 , 4] , 1)
24
1
:
(((1 * 2) * 3) * 4)
2. PYTHON
2.4.2
54
Python ,
CPython , (tail
call optimization, TCO).
, , , . , ,
.
, TCO .
def infinite () :
infinite ()
4
>>> infinite ()
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
...
RuntimeError : maximum recursion depth exceeded
sys.getrecursionlimit() sys.setrecursionlimit(limit).
2.4.3
,
.
, ,
.
def make_adder ( y ) :
def add ( x ) :
return x + y
return add
5
10
def make_counter () :
count = 0
def get () :
return count
def inc () :
count += 1
return get , inc
10
2. PYTHON
15
20
25
55
>>> inc ()
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
File " / tmp / py9637pml " , line 11 , in inc
U n b o u n d L o c a l E r r o r : local variable count referenced before assignment
def make_counter () :
count = 0
def get () :
nonlocal count
return count
def inc () :
count += 1
return get , inc
30
>>>
>>>
>>>
>>>
>>>
1
2.4.4
n
nm (m < n), m
. .
Python:
1
2.4.5
>>> [[ i
[[0 , 0 ,
[0 , 1 ,
[0 , 2 ,
[0 , 3 ,
[0 , 4 ,
10
15
2. PYTHON
2.5
56
, , , ,
. .
import. import :
import module
(top-level)
, .
. dummy,
: .
Listing 2.2: dummy.py
print in dummy module
:
>>> import dummy
in dummy module
>>> import dummy
, .
, .
2
, .
, :
1. , .
2. ,
import.
, .
, . , sys.path.
2. PYTHON
57
,
(public) .
__all__ .
ImportError.
10
( ,
func_global ). m.x m.__dict__[x].
:
__name__ ;
__doc__ None, ;
__file__ , , .
.
, . ,
. ,
, , __init__.py.
Django:
django /
10
__init__ . py
db /
__init__ . py
backends /
models /
transaction . py
utils . py
forms /
__init__ . py
extras /
fields . py
2. PYTHON
58
forms . py
...
15
http /
__init__ . py
m ul ti p ar t pars e r . py
utils . py
template /
__init__ . py
loaders /
base . py
context . py
debug . py
...
20
25
...
import Django:
from django . db import models
from django . http import Http404 , HttpResponse
from django . template import Context
5
. ,
, . ,
. . , from . import mod
pkg, pkg.mod. from ..subpkg2 import mod
pkg.subpkg1, pkg.subpkg2.mod.
from mod import * , _.
, __import__.
2.6
, . , __call__(self, f). , -
. , ,
:
:
def inc ( i ) :
return i + 1
3
inc :
>>> inc (1)
inc called with : (1 ,) , {}
inc returned : 2
2. PYTHON
59
Python @- . :
@debug
def inc ( i ) :
return i + 1
2.6.1
(. currying)
, . ,
:
2
:
@curried
def add (a , b ) :
return a + b
,
:
2
, . , . ,
(lock)
.
2
,
synchronized :
2. PYTHON
import
import
import
lock =
60
time
threading
sys
threading . Lock ()
10
@synchronized ( lock )
def msg ( what , then ) :
print what ,
sys . stdout . flush ()
time . sleep (0.5)
print then ,
sys . stdout . flush ()
,
:
import thread
3
def start_threads () :
thread . s t a r t _ n e w _ t h r e a d ( msg , ( A , B ) )
thread . s t a r t _ n e w _ t h r e a d ( msg , ( C , D ) )
thread . s t a r t _ n e w _ t h r e a d ( msg , ( E , F ) )
>>>
E F
>>>
C D
start_threads ()
A B C D
start_threads ()
A B E F
, : A B . .
,
: , __name__
. ,
, .
10
debug:
@debug
def dummy () :
" Dummy s docstring "
pass
5
, dummy .
debug :
well_behaved
2. PYTHON
61
10
@debug
def dummy () :
" Dummy s docstring "
pass
>>> dummy . __name__
dummy
>>> dummy . __doc__
" Dummy s docstring "
! !
: , . :
.
14
19
@well_behaved
def accepts (* types ) :
def check_types ( f ) :
def wrapped (* args , ** kwargs ) :
for (a , t ) in zip ( args , types ) :
assert isinstance (a , t ) , \
" arg % r does not match % s " % (a , t )
return f (* args , ** kwargs )
return wrapped
return check_types
@well_behaved
def returns ( rtype ) :
def check_types ( f ) :
def wrapped (* args , ** kwargs ) :
result = f (* args , ** kwargs )
assert isinstance ( result , rtype ) , \
" return value % r does not match % s " % ( result , rtype )
return result
return wrapped
return check_types
,
, :
2. PYTHON
2.7
62
-
I propose a new rule for discussions
of object-oriented programming: anyone
who brings up examples of Dog, Bike, Car,
Person, or other real-world objects, unless
they are talking about writing a clone of
The Sims or something, is immediately
shot.
I feel that this new policy will improve
the quality of the discourse enormously.
Once upon a time somewhere on the
Internet
Kragen Javier Sitaker
, klass object. ,
, .
, .
:
def get_object () :
return object
Python ,
. :
class storage ( object ) :
i = 1
def __init__ ( self ) :
self . i = 3
10
>>>
>>>
>>>
>>>
2
>>>
4
s = storage ()
storage . i += 1
s . i += 1
storage . i
storage . i
__init__(self) storage.
self.i = 3 , 3.
-- :
class klass ( object ) :
def __init__ ( self ) :
2. PYTHON
63
self . __private = 1
5
>>> c = klass ()
>>> c . __dict__
{ _ kl as s __ pr i va t e : 1}
klass
>>> c = klass ()
>>> c . m ()
< __main__ . klass object at 0 x1188f10 >
, m
:
class klass ( object ) :
pass
10
def m ( self ) :
print self
>>> c = klass ()
>>> klass . m = m
>>> c . m ()
< __main__ . klass object at 0 x1225990 >
Python :
(static) (class methods). :
class klass ( object ) :
@classmethod
def clsmethod ( cls ) :
print class : , cls
5
10
>>> c = klass ()
>>> klass . clsmethod ()
class : < class __main__ . klass >
>>> c . clsmethod ()
class : < class __main__ . klass >
, ,
. :
class klass ( object ) :
@staticmethod
def staticmethod () :
print static
5
10
>>> c = klass ()
>>> klass . staticmethod ()
static
>>> c . staticmethod ()
static
, .
2. PYTHON
64
2.7.1
property,
:
property ( fget = None , fset = None , fdel = None , doc = None )
10
20
>>> c = klass ()
>>> c . x = 3
>>> c . x
3
>>> klass . x . __doc__
" I m the x property . "
:
class klass ( object ) :
def __init__ ( self ) :
self . _x = 0
4
@property
def x ( self ) :
" I m the x property . "
return self . _x
9
@x . setter
def x ( self , val ) :
self . _x = val
2. PYTHON
65
@x . deleter
def x ( self ) :
del self . _x
14
doc , , . , , ,
property .
2.7.2
MRO
__mro__ type ,
super(). __mro__ , .
class A ( object ) :
def f ( self ) :
print A
5
class B ( A ) :
def f ( self ) :
print B
super (B , self ) . f ()
10
class C ( A ) :
def f ( self ) :
print C
super (C , self ) . f ()
15
class D (B , C ) :
def f ( self ) :
print D
super (D , self ) . f ()
20
>>> D . __mro__
( < class __main__ . D >,
< class __main__ . B >,
< class __main__ . C >,
< class __main__ . A >,
< type object >)
25
30
>>> D () . f ()
D
B
C
A
__mro__ ,
- , .
isinstance(object, class-or-typeor-tuple) issubclass(C, B).
>>> issubclass (D , D ) , issubclass (D , A ) , isinstance ( D () , A )
( True , True , True )
2. PYTHON
2.7.3
66
object.__getattr__(self, name). , .
AttributeError.
object.__setattr__(self, name, value). value
name.
object.__delattr__(self, name).
object.__getattribute__(self, name). . AttributeError
, object.__getattr__(self, name).
class.__instancecheck__(self, instance). True, instance .
class.__subclasscheck__(self, subclass). True, subclass .
2.8
raise, -
.
, Python, : http://docs.python.org/library/exceptions.html.
,
, ,
Exception.
10
2. PYTHON
15
67
try . 46.
2.9
, . __next__
. ,
StopIteration.
__iter__(),
__iter__() next(). __iter__() , ,
, , for.
-, limit:
()
10
15
Python itertools.
:
count(start=0, step=1). , start,
step.
>>>
>>>
>>>
1
>>>
2.5
import itertools
i = itertools . count (1 , 1.5)
i . next ()
i . next ()
cycle(iterable). ,
iterable.
2. PYTHON
>>> i =
>>> for
...
...
...
A B C D
68
repeat(object[, times]).
, times .
iterables.
filter , -
.
>>> i = itertools . ifilter ( None , [1 , 0 , 2 , 0 , 3])
>>> list ( i )
[1 , 2 , 3]
imap(function, *iterables). map. : , iterables .
>>> i = itertools . imap ( lambda x , y : x + y , [1 , 2 , 3 , 4] , [2 , 3 , 4])
>>> list ( i )
[3 , 5 , 7]
izip(*iterables). , i-
i- iterables. , .
>>> i = itertools . izip ( xrange (5) , xrange (1 , 5) )
>>> list ( i )
[(0 , 1) , (1 , 2) , (2 , 3) , (3 , 4) ]
2.10
, .
, yield,
yield .
2. PYTHON
69
next() , yield, , , ,
, yield. next() . ,
yield ( ,
return, ).
, :
10
- :
next(). - ,
. , yield None, .
yield, StopIteration.
send(value). value ,
value yield. , yield, StopIteration, . send(value) , value None.
throw(type[, value[, traceback]]). type , , yield :
raise type , value , traceback
, -.
, StopIteration. - , .
close(). GeneratorExit . -
StopIteration ( , ) GeneratorExit ( ), close.
yield, RuntimeError.
:
class Tree ( object ) :
def __init__ ( self , value , left = None , right = None ) :
self . value = value
self . left = left
2. PYTHON
5
10
15
20
70
25
30
, tail -f.
10
10
15
def consumer ( f ) :
def wrapper (* args , ** kwargs ) :
g = f (* args , ** kwargs )
g . next ()
return g
return wrapper
def follow ( path , target ) :
f = file ( path )
f . seek (0 , 2)
while True :
line = f . readline ()
if not line :
continue
target . send ( line )
@consumer
2. PYTHON
20
25
35
@consumer
def broadcast ( targets ) :
while True :
item = yield
for target in targets :
target . send ( item )
40
if __name__ == __main__ :
follow ( / tmp / fol ,
broadcast ([ grep ( error , echo () ) ,
grep ( warning , echo () ) ]) )
30
71
(coroutines). , , .
15 :
import collections
import sys
import types
5
10
15
20
25
30
15
2. PYTHON
72
try :
if exc :
value = coroutine . throw ( value , * exc )
else :
value = coroutine . send ( value )
except :
if stack :
# send the error back to the " caller "
self . schedule ( stack [0] , stack [1] , * sys . exc_info () )
else :
raise
35
40
45
2.10.1
, .
. , ;
, - ,
yield. , , ,
.
>>> sum ( i * i for i in range (10) )
285
2.11
, . owner,
-.
d.__get__(self, instance, owner). owner , d. instance , , None, owner. AttributeError.
d.__set__(self, instance, value). value
instance.
d.__delete__(self, instance). , instance.
x a : a.__dict__[x], type(a).__dict__[x],
, . , AttributeError.
2. PYTHON
73
x a , a.x
type(a).__dict__[x].__get__(a, type(a)), a , a.__dict__[x].__get__(None,
a), a .
:
class RevealAccess ( object ) :
def __init__ ( self , initval = None , name = var ) :
self . val = initval
self . name = name
5
15
20
25
, x
.
Python . :
10
15
20
2. PYTHON
25
staticmethod
classmethod :
10
15
:
class WellTyped ( object ) :
of_type = object
3
13
18
23
28
33
74
2. PYTHON
75
, , :
10
15
>>> t = Test ()
>>> t . i = 1.0
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
File " / tmp / py6835YLA " , line 19 , in __set__
File " / tmp / py6835YLA " , line 24 , in _check
ValueError
>>> t . i = 2
>>> t . i
2
>>> t . pi = -1
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
File " / tmp / py6835YLA " , line 19 , in __set__
File " / tmp / py6835YLA " , line 36 , in _check
ValueError
2.12
Python , .
.
>>> class klass ( object ) :
...
pass
4
>>> c = klass ()
>>> c
< __main__ . klass object at 0 xc14a90 >
>>> klass
< class __main__ . klass >
>>> id ( klass )
12861152
id , , ,
, .
,
. Python type.
>>> object . __class__
< type type >
>>> type ( object )
< type type >
type:
Python ( class), . -
.
2. PYTHON
76
type.
, class.
# prototype
type ( name , bases , dict )
name , bases (
), dict ,
, .
__metaclass__.
() , , ,
( self),
. cls.
, , .
10
15
20
25
30
, __new__ __init__ .
__call__ .
class, Python
. , -
2. PYTHON
77
. Python :
1. dict[__metaclass__] , .
2. , , ( __class__, ,
).
3. , __metaclass__, .
,
.
__metaclass__ ,
(callable) , .
def meta ( name , bases , dct ) :
# setting useless attr
dct [ foo ] = bar
return type ( name , bases , dct )
5
10
Singleton :
class S i n g l e t o n M e t a c l a s s ( type ) :
instance = None
10
Python, ,
, , . : , , ,
, , ORM / .
,
, , dump_file,
JSON.
import json
class I n i t F r o m D u m p M e t a ( type ) :
def __new__ ( metacls , name , bases , dct ) :
if dump_file in dct :
try :
dump_file = file ( dct [ dump_file ])
2. PYTHON
78
10
/tmp/dump.json :
{ " one " : 1 , " two " : 2 }
:
class I n i t F r o m D u m p C l a s s ( object ) :
__metaclass__ = I n i t F r o m D u m p M e t a
dump_file = / tmp / dump . json
:
1
>>> I n i t F r o m D u m p C l a s s . one
1
>>> I n i t F r o m D u m p C l a s s . two
2
2.13
Python .
. , ,
( , dict ) __dict__.
class klass ( object ) :
pass
10
>>> c = klass ()
>>> c . attr = some
>>> print c . __dict__
{ attr : some }
>>> print klass . __dict__
{ __dict__ : < attribute __dict__ of klass objects > ,
__module__ : __main__ ,
__weakref__ : < attribute __weakref__ of klass objects > ,
__doc__ : None }
, , :
class BaseA ( object ) :
pass
3
2. PYTHON
13
18
79
inspect.
import inspect
def f (a , b , c =3) :
return a + b + c
5
[1] M. Pilgrim, Dive into Python 3. Apress, 2nd ed., 2009.
[2] Official Python Tutorial. http://docs.python.org/tutorial/index.html.
[3] Python Library Reference. http://docs.python.org/library/index.html.
[4] Python Language Reference. http://docs.python.org/reference/index.html.
80
3.1
3.1.1
,
. () , . ;
.
, , .
, . , .
1
int y = 0 , z = 0;
co
x=y+z;
//
y = 1; z = 2;
oc ;
x = y + z y
z, x 0, 1, 2
3.
, .
( int) (,
), .
: , .
81
3.
82
.
, .
( ).
, , ,
, , .
, e ,
, ,
. , e , e,
, , . , x = e
, (,
), .
, , , .
.
.
, . ,
,
. x = e
, e , x , e
, x.
,
,
. , e , x , , ,
. , e , , , ,
; .
int x = 0 , y = 0;
co x = x + 1; // y = y + 1; oc ;
int x = 0 , y = 0;
co x = y + 1; // y = y + 1; oc ;
:
, , . .
,
, ,
.
3.
83
h i. , hei ,
e .
await:
hawait ( B ) S ;i
(delay condition), S , .
:
hawait ( s > 0) s = s - 1;i
S ,
, S , S ; hS; i
, S.
await :
hawait ( B ) ;i
B , ,
hawait (B);i
while ( not B ) ;
(spin loop).
, B. , ,
. () , await,
, .
await B.
, B . B ,
. , ,
,
.
3.1.2
(fairness), ,
.
3.
84
(unconditional fairness). , .
(weak fairness). , : 1) , 2)
,
, , .
(strong fairness). , 1) , 2)
, .
3.2
,
, . ,
.
( ),, , .
3.2.1
. n ,
. ,
. , ,
:
process CS [ i = 1 to n ] {
while ( true ) {
;
;
;
;
}
}
, .
, :
(1) (mutual exclusion). .
(2) ( ) (freedom from livelocks).
,
.
(3) . , ,
.
3.
85
12
17
process CS2 {
while ( true ) {
< await (! in1 ) in2 = true ; > /* */
;
in2 = false ; /* */
;
}
}
3.2.2
, 3.1, . n n .
:
, . , ,
, .
lock , , . :
lock == (in1 in2)
lock in1 in2, 3.1 , 3.2.2.
, 3.2.2,
3.1 ,
.
3.
86
Listing 3.2:
bool lock = false ;
10
15
process CS1 {
while ( true ) {
< await (! lock ) lock = true ; > /* */
;
lock = false ; /* */
;
}
}
process CS2 {
while ( true ) {
< await (! lock ) lock = true ; > /* */
;
lock = false ; /* */
;
}
}
-
lock in1 in2, 3.2.2,
, , ,
. ,
-.
- (test-and-set, TS)
lock .
TS lock,
, lock.
TS :
1
TS,
3.2.2 , 3.3. ,
, (spin lock),
, .
Listing 3.3:
bool lock = false ; /* */
10
process CS [ i = 1 to n ] {
while ( true ) {
while ( TS ( lock ) ) skip ; /* */
;
lock = false ; /* */
;
}
}
3.
87
, (4) .
, , lock .
, , . ,
, . , 3.3 .
,
:
.
.
--
3.3 , ,
. , lock.
, ,
.
TS lock, .
, TS
, .
- , -. lock ,
TS.
Listing 3.4: --
bool lock = false ; /* */
10
process CS [ i = 1 to n ] {
while ( true ) {
while ( lock ) skip ; /* */
while ( TS ( lock ) ) {
while ( lock ) skip ;
}
;
lock = false ; /* */
;
}
}
await
hS;i,
. CSenter ; CSexit . hS;i :
3.
88
CSenter ;
S;
CSexit ;
, , , S ( , S),
. , h i
CSenter CSexit.
hawait(B) S;i. , , B , S.
S, B .
, , S. B, ,
.
2
CSenter ;
while (! B ) { CSexit ; Delay ; CSenter ; }
S;
CSexit ;
, , ,
B S, , S,
.
, B . , B , . , ,
, , , , B , . B
S B . Delay , .
.
3.2.3
, ,
. (4) . , , , .
, , ,
, ,
. , ,
.
: , .
,
(round-robin) , , , , .
3.
89
( 3.1).
, , ,
, . ,
, , . ,
, .
( ) , ,
. , , .
, 3.1.
.
- , ,
, ,
.
, ,
, ,
.
last , , CS1
CS2 . , . . it1 it2 , .
, 3.5.
Listing 3.5: :
1
11
16
21
3.5 ,
await. , await
, .
, await 3.5 ,
3.
90
.
. .
, CS1 ,
. CS1 , in2 , in2 .
CS2 last 2; ,
, in2 .
, last == 2 , ,
last , CS1 . ,
, CS1 ,
. ( CS2 .)
,
await while, ,
.
( 3.6).
Listing 3.6: :
bool in1 = false , in2 = false ;
int last = 1;
3
process CS1 {
while ( true ) {
last = 1; in1 = true ; /* */
while ( in2 and last == 1) skip ;
;
in1 = false ; /* */
;
}
}
13
18
process CS2 {
while ( true ) {
last = 2; in2 = true ; /* */
while ( in1 and last == 2) skip ;
;
in2 = false ; /* */
;
}
}
.
.
, n ,
n 1 .
, , .
, n 1 , ,
.
in[1:n] last[1:n] . in[i] , CS[i]. last[j] ,
j. 3.2.3. for n-1 . for CS[i]
. CS[i] ,
, CS[i] , j. j ,
CS[i] , CS[i]
3.
91
. , n 1 , n 2 . ,
n .
Listing 3.7: n
int in [1: n ] = ([ n ] 0) , last [1: n ] = ([ n ] 0) ;
3
13
18
process CS [ i = 1 to n ] {
while ( true ) {
for [ j = 1 to n ] { /* */
/* , i j
*/
last [ j ] = i ; in [ i ] = j ;
for [ k = 1 to n st i != k ] {
/* , k
i j */
while ( in [ k ] >= in [ i ] and last [ j ] == i ) skip ;
}
}
;
in [ i ] = 0; /* */
;
}
}
n ,
. ,
,
, ,
.
, () .
number next 1, turn[1:n]
0. , CS[i] turn[i] number
number 1. () , . CS[i] ,
next .
CS[i] 1 next, .
, 3.2.3.
number next ,
.
1
, turn .
, turn[i] next, . . .
3.
92
. , , ,
, .
Listing 3.8: :
int number = 1 , next = 1 , turn [1: n ] = ([ n ] , 0) ;
## -- TICKET (. )
10
process CS [ i = 1 to n ] {
while ( true ) {
< turn [ i ] = number ; number = number + 1; >
< await ( turn [ i ] == next ) : >
;
< next = next + 1; >
;
}
}
3.2.3 . await
, . ,
next, , . ,
( number ) .
,
. , .
(fetch-and-add, FA), :
FA ( var , incr ) {
< int tmp = var ;
var = var + incr ;
return tmp ; >
}
Listing 3.9: :
int number = 1 , next = 1 , turn [1: n ] = ([ n ] , 0) ;
10
process CS [ i = 1 to n ] {
while ( true ) {
turn [ i ] = FA ( number , 1) ; /* */
while ( turn [ i ] != next ) skip ;
;
next = next + 1; /* */
;
}
}
, , .
. ,
:
turn [ i ] = number ; < number = number + 1; >
3.
93
number ,
. ,
!
, .
: .
, . , CSenter , CSexit .
5.4.2 .
CSenter ;
turn [ i ] = number ;
number = number + 1;
CSexit ;
, ,
-.
- , ,
.
, . ,
, CSenter.
, next turn[i].
3.2.4
3.3
3.3.1
3.3.2
3.3.3
3.3.4
3.3.5
4.1
TCP
4.1.1
1. . (passive open).
2. (active open), SYN,
. IP, TCP TCP.
94
4.
95
3. SYN
SYN, . SYN ACK
.
4. SYN .
socket
connect
SYN J
CK J+1
SYN K, A
ACK K+1
accept,
accept
. 4.1: TCP
(c. . 4.1), TCP (TCP three-way handshake).
4.1.2
TCP
SYN TCP. :
MSS. (maximum
segment size, MSS) ,
TCP .
(Window scale option). ,
TCP, 65535, 16 .
. , TCP
014 ,
(65535 214 ).
(Timestamp option). , ,
, .
4.1.3
TCP
.
1. (active close). TCP
FIN.
4.
96
4.1.4
TCP
. 4.2 . 97.
4.1:
CLOSED
LISTEN
SYN_SENT
SYN_RECEIVED
ESTABLISHED
CLOSE_WAIT
.
;
;
, ;
, ;
;
, ,
FIN_WAIT_1
CLOSING
LAST_ACK
FIN_WAIT_2
TIME_WAIT
4.1.5
TIME_WAIT
4.
97
CLOSED
Close
e
YN
/S
en
op
Close
tiv
Ac
Passive open
Timeout/RST
LISTEN
Send /SYN
SYN/SYN + ACK
SYN/SYN + ACK
SYN_RCVD
SYN_SENT
SYN + ACK/ACK
ACK
ACK
Close/FIN
ESTABLISHED
FIN/ACK
Close/FIN
CLOSE_WAIT
FIN_WAIT_1
ACK
Close/FIN
ACK
FIN_WAIT_2
FIN +
ACK/ACK
LAST_ACK
CLOSING
ACK
FIN/ACK
TIME_WAIT
. 4.2: TCP
MSL .
TIME_WAIT:
TCP;
4.
98
, .
, ACK . FIN, ,
ACK .
, RST, .
, ,
. TCP
.
, TCP ,
TIME_WAIT.
4.2
UDP
4.2.1
UDP TCP
UDP:
UDP , UDP , .
UDP .
. TCP 10 ,
.
4.3
POSIX API
4.3.1
DAYTIME
DAYTIME .
IPv4- .
# include < stdio .h >
# include < stdlib .h >
4.
99
10
15
20
1024
if ( argc != 3)
error (1 , 0 , " usage : date - client - basic < server - ip > < port > " ) ;
25
35
40
45
50
if ( n < 0)
error (1 , errno , " read " ) ;
55
4.
100
. DAYTIME ,
1 :
% nc6 -l -- half - close -- continuous -- exec date -p 45678
:
% date - client - basic 127.0.0.1 45678
Fri Feb 3 01:22:43 FET 2012
Voil`
a! ! , .
socket
/ socket,
.
# include < sys / socket .h >
int socket ( int family , int type , int protocol ) ;
, -1 . family
.
4.2: family connect
AF_INET
AF_INET6
AF_LOCAL
AF_ROUTE
AF_KEY
IPv4
IPv6
Unix
4.3:
SOCK_STREAM
SOCK_DGRAM
SOCK_SEQPACKET
SOCK_RAW
()
protocol
, .
family type . socket
, . , . , .
1
man.
4.
101
4.4: protocol
IPPROTO_TCP
IPPROTO_UDP
IPPROTO_SCTP
TCP
UDP
SCTP
connect
connect .
# include < sys / socket .h >
int connect ( int sockfd , const struct sockaddr * servaddr , socklen_t addrlen ) ;
sockfd , socket.
IP- .
bind connect,
, IP- .
TCP connect .
, . :
1. SYN, ETIMEDOUT.
2. SYN RST, , . ECONNREFUSED RST.
3. SYN ICMP
- . , SYN . ,
ICMP EHOSTUNREACH,
ENETUNREACH.
inet_pton inet_ntop
IP-, , , . p n .
# include < arpa / inet .h >
int inet_pton ( int family , const char * str , void * addr ) ;
4.
# define
# define
4.3.2
I NE T_ A DD RS T RL EN
INET6_ADDRSTRLEN
102
16
46
DAYTIME ,
IPv4-, IPv6- ;
,
/etc/services.
# include < stdio .h >
# include < stdlib .h >
# include < string .h >
5
10
15
20
1024
25
30
35
40
45
50
if ( close ( server_socket ) != 0)
error (1 , errno , " close " ) ;
} while (( addr = addr - > ai_next ) != NULL ) ;
if ( addr == NULL )
error (1 , 0 , " was not able to connect to specified network address and
service " ) ;
4.
103
freeaddrinfo ( addrs ) ;
while (( n = read ( server_socket , buffer , BUFFER_SIZE ) ) > 0) {
buffer [ n ] = \0 ;
if ( printf ( " % s " , buffer ) < 0)
error (1 , 0 , " error of printing to stdout " ) ;
}
55
if ( n < 0)
error (1 , errno , " read " ) ;
60
65
DAYTIME :
% date - client localhost 45678
Fri Feb 3 02:06:13 FET 201
getaddrinfo
. sockaddr. getaddrinfo
.
# include < netdb .h >
int getaddrinfo ( const char * node , const char * service ,
const struct addrinfo * hints ,
struct addrinfo ** res ) ;
res addrinfo.
10
struct addrinfo {
int
ai_flags ;
int
ai_family ;
int
ai_socktype ;
int
ai_protocol ;
size_t
ai_addrlen ;
struct sockaddr * ai_addr ;
char
* ai_canonname ;
struct addrinfo * ai_next ;
};
/*
/*
/*
/*
/*
/*
/*
/*
AI_PASSIVE , AI_CANONNAME */
AF_xxx */
SOCK_xxx */
0 or IPPROTO_xxx for IPv4 or IPv6 */
ai_addr length */
pointer to canonical name */
pointer to socket address structure */
pointer to next structure in list */
node , (-
IPv4 IPv6). service
, , .
hints , addrinfo, ,
.
ai_flags ( AI_xxx, );
ai_family ( AF_xxx);
ai_socktype ( SOCK_xxx);
ai_protocol.
4.
104
ai_flags:
AI_PASSIVE , ;
AI_CANONNAME ;
4.3.3
DAYTIME
.
# include < stdio .h >
# include < stdlib .h >
# include < string .h >
5
10
15
20
25
30
# define BUFFER_SIZE
# define BACKLOG
1024
5
35
40
45
50
4.
105
55
if ( addr == NULL )
error (1 , 0 , " was not able to bind to specified network address and
service " ) ;
freeaddrinfo ( addrs ) ;
60
for (;;) {
socket_length = sizeof ( client_addr ) ;
if (( client_socket = accept ( listen_socket ,
( struct sockaddr *) & client_socket ,
& socket_length ) ) < 0)
error (1 , errno , " accept " ) ;
70
75
80
, ,
,
. TIME_WAIT. setsockopt
.
:
% date - server 45678
# in another shell
% nc6 localhost 45678
Fri Feb 3 07:37:05 2012
: !
bind
bind , IP
.
# include < sys / socket .h >
4.
106
int bind ( int sockfd , const struct sockaddr * addr , socklen_t addrlen ) ;
,
.
bind IP- . IP . IP-,
IP-.
: ,
IP-.
, bind . IP- ,
IP-,
.
IPv4 , INADDR_ANY.
struct sockaddr_in addr ;
servaddr . sin_addr . s_addr = htonl ( INADDR_ANY ) ;
listen
listen TCP .
1. socket, , ,
, connect. listen ,
.
2. ,
.
# include < sys / socket .h >
int listen ( int sockfd , int backlog ) ;
backlog, , :
1. (incomplete connection queue), SYN, ,
TCP.
2. (complete connection queue), ,
TCP.
,
. ,
.
accept,
, .
:
4.
107
,
.
, SYN, TCP
SYN RST. ,
, TCP SYN,
, .
, , ,
accept, TCP-,
.
accept
accept TCP .
, (
).
# include < sys / socket .h >
int accept ( int sockfd , struct sockaddr * addr , socklen_t * addrlen ) ;
4.3.4
, - (, ). -.
-
:
(
), -.
.
TCP , ,
-.
TCP, UDP, -.
select
, ,
, , .
4.
108
, , , . timeval :
struct timeval {
long tv_sec ;
long tv_usec ;
};
/* seconds */
/* microseconds */
:
1. , . timeout NULL.
2. , -
- .
3. . timeout timeval, .
readfds, writefds exceptfds ,
. :
void
void
void
int
/*
/*
/*
/*
clears a set */
add a descriptor to a set */
remove a descriptor from a set */
tests whether a descriptor is
part of a set */
FD_SETSIZE
fd_set.
, :
1.
(low water-mark).
2. .
.
3. , .
4. , .
, :
1.
,
, .
2. , , . SIGPIPE.
3. , .
, ,
, .
4.
109
,
TCP
t
t
t
t
t
t
t
t
poll
poll select.
# include < poll .h >
int poll ( struct pollfd * fds , nfds_t nfds , int timeout ) ;
. pollfd, , fd.
struct pollfd {
int
fd ;
short events ;
short revents ;
};
/* file descriptor */
/* requested events */
/* returned events */
events
revents
POLLIN
POLLPRI
r
r
r
r
POLLOUT
r
r
r
POLLERR
POLLHUP
POLLNVAL
timeout , .
4.
110
<0
0
>0
epoll
epoll , Linux 2.5.44. , select poll.
kqueue FreeBSD.
# include < sys / epoll .h >
int epoll_create ( int size ) ;
10
events
/* epoll events */
/* user data variable */
, :
EPOLLIN. .
EPOLLOUT. .
EPOLLRDHUP.
.
EPOLLPRI. .
4.
111
EPOLLERR. . epoll_wait ,
events.
EPOLLHUP. . epoll_wait ,
events.
EPOLLET. edge-triggered . Level-triggered
.
EPOLLONESHOT. , epoll_wait, ,
epoll_ctl EPOLL_CTL_MOD.
:
1. rfd, , epoll.
2. 2kB .
3. epoll_wait, , rfd .
4. 1kB .
5. epoll_wait.
level-triggered epoll_wait , edge-triggered .
# include < sys / epoll .h >
int epoll_wait ( int epfd , struct epoll_event * events ,
int maxevents , int timeout ) ;
, epoll-, epfd
. events epoll_event, ,
maxevents. timeout timeout poll.
4.3.5
! ,
inetd.
! .
! .
% ,
.
% , , .
4.
112
Python. , ,
, /.
echo-, . - :
import argparse
, ,
:
import socket
import sys
4
14
def l i s t e n i n g _ s o c k e t ( port ) :
host = None
family = socket . AF_UNSPEC
socket_type = socket . SOCK_STREAM
protocol = 0
flags = socket . AI_PASSIVE
server_socket = None
for addrinfo in socket . getaddrinfo ( host , port , family , socket_type ,
protocol , flags ) :
family , socket_type , protocol , canonical_name , addr = addrinfo
try :
19
24
29
34
if server_socket is None :
print could not open socket
sys . exit (1)
return server_socket
: ,
.
4.
113
aux.
:
import os
import signal
import aux
5
def main () :
args = aux . parse_args ( Echo server with fork processing model . )
server_socket = aux . l i s t e n i n g _ s o c k e t ( args . port )
10
15
20
if os . fork () == 0:
server_socket . close ()
aux . communicate ( client_socket )
client_socket . close ()
return
else :
client_socket . close ()
if __name__ == __main__ :
main ()
fork - , ,
. :
1. SIGCHLD,
( );
2. SIGCHLD, , , os.waitpid
(-1, os.WNOHANG).
FSM
FSM (Finite State Machine) ,
(select, poll ..).
! CPU.
% .
% FSM, ,
.
! , FSM .
% .
,
.
4.
Listing 4.1: select
import select
import aux
5
10
def main () :
args = aux . parse_args ( Echo server with select - processing model . )
server_socket = aux . l i s t e n i n g _ s o c k e t ( args . port )
soc ket_to _data = {}
cli ent_so ckets = []
all_sockets = [ server_socket ]
while True :
readable , _ , _ = select . select ( all_sockets , [] , [] , 0.05)
15
if server_socket in readable :
client_socket , _ = server_socket . accept ()
soc ket_to _data [ client_socket ] =
cli ent_so ckets . append ( client_socket )
all_sockets . append ( client_socket )
20
30
35
40
45
if __name__ == __main__ :
main ()
Listing 4.2: poll
import select
import aux
5
10
def main () :
args = aux . parse_args ( Echo server with poll - processing model . )
server_socket = aux . l i s t e n i n g _ s o c k e t ( args . port )
server_fileno = server_socket . fileno ()
fil eno_to _data = {}
114
4.
115
f i l e n o _ t o _ s o c k e t = {}
read_poll = select . poll ()
read_poll . register ( server_fileno , select . POLLIN )
15
20
while True :
for fileno , eventmask in read_poll . poll (50) :
if fileno == server_fileno :
client_socket , _ = server_socket . accept ()
client_fileno = client_socket . fileno ()
fil eno_to _data [ client_fileno ] =
f i l e n o _ t o _ s o c k e t [ client_fileno ] = client_socket
25
30
35
40
45
50
55
60
if __name__ == __main__ :
main ()
! .
! .
4.
116
% .
% .
, . , fork - .
import threading
import aux
5
10
15
def main () :
args = aux . parse_args ( Echo server with threaded - processing model . )
server_socket = aux . l i s t e n i n g _ s o c k e t ( args . port )
20
while True :
client_socket , client_addr = server_socket . accept ()
worker = Worker ( client_socket )
worker . start ()
25
if __name__ == __main__ :
main ()
FSM c
! -
, .
.
! .
% FSM.
Linux epoll.
Listing 4.3: epoll
import select
import aux
5
10
def main () :
args = aux . parse_args ( Echo server with epoll - processing model . )
server_socket = aux . l i s t e n i n g _ s o c k e t ( args . port )
server_fileno = server_socket . fileno ()
fil eno_to _data = {}
f i l e n o _ t o _ s o c k e t = {}
4.
117
20
while True :
for fileno , eventmask in read_epoll . poll (0.05) :
if fileno == server_fileno :
client_socket , _ = server_socket . accept ()
client_fileno = client_socket . fileno ()
fil eno_to _data [ client_fileno ] =
f i l e n o _ t o _ s o c k e t [ client_fileno ] = client_socket
25
30
35
40
45
50
55
60
write_epoll . close ()
if __name__ == __main__ :
main ()
4.4
TCP/IP :
(application): HTTP, FTP . .;
4.
118
.? .?
hostid
127
loopback
-1
-1
( )
netid
-1
netid
4.4.1
H1 H2, , IP H2, .
4.
119
H1 H3, H1
R1. , H1
, , 2,
R1, ,
H3.
H1
H2
R2
1
H3
H4
H5
R1
2
. 4.3:
, .
. -, . , ,
, .
:
1
11
% netstat -i
Kernel Interface table
Iface
MTU ... Flg
eth1
1500 ... BMRU
lo
16436 ... LRU
ppp0
1400 ... MOPRU
% route -n
Kernel IP routing table
Destination
Gateway
0.0.0.0
0.0.0.0
81.25.32.68
192.168.1.1
91.187.0.1
0.0.0.0
127.0.0.0
127.0.0.1
Genmask
0.0.0.0
2 55 . 25 5. 2 55 . 25 5
2 5 5. 25 5 .2 5 5. 25 5
255.0.0.0
Flags
U
UGH
UH
UG
Metric
0
0
0
0
Ref
0
0
0
0
Use
0
0
0
0
Iface
ppp0
eth1
ppp0
lo
,
, ,
ppp0. ,
81.25.32.68 ( H) 192.168.1.1 ( G).
91.187.0.1 ( H) ,
ppp0. 127 127.0.0.1.
4.4.2
4.
120
.
.
, ,
, .
.
( ), ,
.
0
15 16
23 24
31
. 4.4:
, , .
, , , .
4.4.3
. 255.255.255.255.
, , ,
.
.
, .
. ,
. , .
.
, . ,
.
4.4.4
4.
4.4.5
121
NAT
IP-.
RFC 1918 , :
10.0.0.010.255.255.255 ( 10/8);
172.16.0.0172.31.255.255 ( 172.16/12);
192.168.0.0192.168.255.255 ( 192.168/16).
,
, IP-.
, (NAT, Network Address Translation).
IP-. NAT
:
.
, .
. NAT IP ,
.
PAT (Port Address Translation, ). , . ,
,
.
4.4.6
ARP
4.
122
6. ARP - ,
IP- . ,
MAC-.
7. , .
ARP- tcpdump:
ARP
ARP .
:
% arp -a
? (192.168.1.1) at 00:26:5 a : e0 :17: d9 [ ether ] on eth1
4.4.7
ICMP
4.
123
10
15
20
25
30
35
40
4.
124
45
50
55
if __name__ == __main__ :
parser = argparse . Argum entPar ser ( description = traces path to a network
host )
parser . add_argument ( host , metavar = host , type = unicode ,
help = host which is to trace path to )
parser . add_argument ( -p , -- port , dest = port , metavar = port ,
help = port to use for connection [ default : %( default )
d],
default =45678 , type = int )
parser . add_argument ( -m , -- max - hops , dest = hops , metavar = hops ,
help = max hops [ default : %( default ) d ] ,
default =30 , type = int )
60
4.4.8
DHCP
4.4.9
DNS
4.
125
arpa
org
wikipedia
in-addr
81
en
www
example
www
25
32
34
.
. , FQDN (Fully Qualified Domain Name). . , www.example.com
(), www.example.com. ().
. () ; , . .
:
. : .com, .org, .net, .biz.
. , .
.arpa. , .
DNS
. . ,
, . ,
,
- . , ,
.
, DNS, . , DNS- , .
DNS- , , .
. ,
, . .
DNS- . , DNS-
.
DNS- , ,
, .
4.
126
. , , . .
DNS-, , /etc/resolv.conf. :
nameserver 81.25.32.34
nameserver 81.25.32.9
IP- . , ,
. ,
.
DNS
DNS. :
NAME
TTL (Time To Live)
,
DNS-
,
TYPE
CLASS
RDLEN
RDATA
:
A (address record ). IP.
AAAA (IPv6 address record ). IPv6.
CNAME (canonical name record ). . .
MX (mail exchange). .
NS (name server ). DNS- .
PTR (pointer ). IP- .
DNS- host
nslookup.
% host 81.25.32.34
34.32.25.81. in - addr . arpa domain name pointer ns1 . infonet . by .
% host -t mx adsl . by
adsl . by mail is handled by 10 mail . adsl . by .
% nslookup - type = ptr 34.32.25.81. in - addr . arpa
Server :
81.25.32.34
4.
Address :
10
127
4.5
4.5.1
- - :
1. alarm, SIGALRM, .
2. - select,
, read write.
3. SO_RCVTIMEO SO_SNDTIMEO.
/,
connect, TCP
( 75 ).
4.5.2
.
TCP 40 ,
4000%.
, . , . RFC 1122 , ,
. : .
TCP . , TCP
ACK ,
. ACK .
TP ,
, / RT T + TP .
,
, , , .
, , .
4.5.3
4.
128
1. : 0 1023.
IANA.
2. : 1024 49151. IANA, IANA
.
3. , : 49152 65535.
4.6
ps
. , :
wchan , . -, . *, , ps
.
ping
ping ICMP ECHO_REQUEST
( ) ICMP ECHO_RESPONSE
.
% ping -c 3 informatics . by
PING informatics . by ( 9 1 . 1 4 9 . 1 5 7 . 1 5 2 ) 56(84) bytes of data .
64 bytes from vh24 . hoster . by ( 9 1 . 1 4 9 . 1 5 7 . 1 5 2 ) : icmp_req =1 ttl =59 time =403 ms
64 bytes from vh24 . hoster . by ( 9 1 . 1 4 9 . 1 5 7 . 1 5 2 ) : icmp_req =2 ttl =59 time =399 ms
64 bytes from vh24 . hoster . by ( 9 1 . 1 4 9 . 1 5 7 . 1 5 2 ) : icmp_req =3 ttl =59 time =267 ms
--- informatics . by ping statistics --3 packets transmitted , 3 received , 0% packet loss , time 1999 ms
rtt min / avg / max / mdev = 2 6 7 . 6 5 1 / 3 5 6 . 9 1 6 / 4 0 3 . 5 1 2 / 6 3 . 1 4 0 ms
traceroute
traceroute .
UDP c TTL 1 30 (
) TTL (ICMP
TIME_EXCEEDED).
1
% traceroute informatics . by
traceroute to informatics . by ( 9 1 . 1 4 9 . 1 5 7 . 1 5 2 ) , 30 hops max , 60 byte packets
1 10.10.224.1 (10.10.224.1) 459.626 ms 679.630 ms 683.505 ms
2 * * *
3 77.74.33.114 (7 7.74.3 3.114) 687.141 ms 1246.943 ms 1250.856 ms
4 as6697 -2. by - ix . net ( 1 9 5 . 1 3 7 . 1 8 0 . 2 5 3 ) 1254.780 ms 1282.746 ms 1287.441
ms
5 gi15 -0 -0. ne1 -1 -2. net . belpak . by (93.84.125.9) 1287.400 ms 1290.625 ms
1294.567 ms
6 gw2 . datacenter . beltelecom . by (9 3 .8 4. 1 25 .1 6 5) 1294.530 ms 255.403 ms
327.064 ms
7 vh24 . hoster . by ( 9 1 . 1 4 9 . 1 5 7 . 1 5 2 ) 334.976 ms 386.862 ms 762.791 ms
4.
129
route
IP-.
1
netstat
, ,
, ..
% netstat - nr
Kernel IP routing table
Destination
Gateway
10.6.6.6
0.0.0.0
169.254.0.0
0.0.0.0
0.0.0.0
10.6.6.6
Genmask
2 5 5. 25 5 .2 5 5. 25 5
255.255.0.0
0.0.0.0
Flags
UH
U
UG
MSS
0
0
0
Window
0
0
0
irtt
0
0
0
Iface
ppp0
ppp0
ppp0
ifconfig
ifconfig .
, ifconfig . ,
; -a,
, . .
netcat
TCP UDP, ,
. cat /.
tcpdump
.
.
Listing 4.5: tcpdump
% tcpdump -i lo
tcpdump : verbose output suppressed , use -v or - vv for full protocol decode
listening on lo , link - type EN10MB ( Ethernet ) , capture size 65535 bytes
2 2: 02 : 04 .0 2 19 05 IP localhost . localdomain .43849 > localhost . localdomain .6600:
Flags [ P .] , seq 2463307991:2463307998 , ack 2463842528 , win 770 , options [
nop , nop , TS val 12929880 ecr 12929629] , length 7
2 2: 02 : 04 .0 2 28 45 IP localhost . localdomain .6600 > localhost . localdomain .43849:
Flags [ P .] , seq 1:156 , ack 7 , win 512 , options [ nop , nop , TS val 12929880
ecr 12929880] , length 155
2 2: 02 : 04 .0 2 28 78 IP localhost . localdomain .43849 > localhost . localdomain .6600:
Flags [.] , ack 156 , win 770 , options [ nop , nop , TS val 12929880 ecr
12929880] , length 0
^C
3 packets captured
6 packets received by filter
0 packets dropped by kernel
4.
130
tcpreplay
, tcpdump.
.
iperf
TCP UDP . TCP, UDP. ,
.
sysctl
, ,
. , .
/etc/sysctl.conf, .
[1] . , TCP/IP. , 2001.
[2] . . , . , . . , UNIX. .
, 3- ., 2007.
[3] . . , . . , TCP/IP, 3.
/ Linux/POSIX. , 2002.
[4] W. Richard Stevens, TCP/IP Illustrated. Volume 1. The protocols. Addison-Wesley, 1994.
131
5.1
- . , . Haskell :
data Color = R
| B
deriving Show
5
data Tree e = E
| T Color ( Tree e ) e ( Tree e )
deriving Show
,
- ,
. :
1. .
2. .
3. .
4. .
5.1.1
. , :
empty :: Tree e
empty = E
3
132
5.
133
z
d
y
. 5.1:
, 5.1, .
5.1 ,
.
balance. , ,
.
balance
balance
balance
balance
balance
balance
e
R
R
R
R
->
(T
(T
(T
(T
Tree e
B a x b)
B a x b)
B a x b)
B a x b)
y
y
y
y
(T
(T
(T
(T
B
B
B
B
c
c
c
c
z
z
z
z
d)
d)
d)
d)
insert : , ,
, balance,
.
insert :: Ord e = > e -> Tree e -> Tree e
5.
134
, .
fromList :: Ord e = > [ e ] -> Tree e
fromList = foldl ( flip insert ) E
3
main :: IO ()
main = do
putStrLn $ show $ fromList [9 , 8 , 7 , 4 , 5 , 6 , 3 , 2 , 1 , 0]
, :
T B (T B (T R (T B E 0 E) 1 (T B E 2 E)) 3 (T B E 4 E)) 5 (T B (T B (T R E 6
E) 7 E) 8 (T B E 9 E))
5.2
(trie) ,
, , , . ,
, .
, .
.
t
o
i
n
to
te
a
tea
in
n
d
ted
ten
inn
, . , O(m), m
.
5.2.1
Data.Map,
, Data.Maybe:
5.
135
:
1
, :
empty :: Ord k = > Trie k v
empty = Trie Nothing Map . empty
3
member lookup.
- insert:
-, , .
fromList :: Ord k = > [([ k ] , v ) ] -> Trie k v
fromList = foldl (\ t (k , v ) -> insert k v t ) empty
4
main :: IO
main = do
let keys
let trie
putStrLn
()
= [ " tea " , " ted " , " ten " , " inn " , " te " , " " ]
= fromList [ (k , True ) | k <- keys ]
$ show trie
main :
Trie ( Just True ) ( fromList [( i , Trie Nothing ( fromList [( n , Trie Nothing (
fromList [( n , Trie ( Just True ) ( fromList []) ) ]) ) ]) ) ,( t , Trie Nothing (
fromList [( e , Trie ( Just True ) ( fromList [( a , Trie ( Just True ) (
fromList []) ) ,( d , Trie ( Just True ) ( fromList []) ) ,( n , Trie ( Just True )
( fromList []) ) ]) ) ]) ) ])
- :
5.
136
, , delete.
deleteAll :: Ord k = > [[ k ]] -> Trie k v -> Trie k v
deleteAll keys trie = foldl ( flip delete ) trie keys
main :: IO
main = do
let keys
let trie
putStrLn
()
= [ " tea " , " ted " , " ten " , " inn " , " te " , " " ]
= fromList [ (k , True ) | k <- keys ]
$ show $ deleteAll keys trie
, :
Trie Nothing ( fromList [])
5.3
(Bloom filter ) , . ,
, .
, , .
. .
m - h1 , ..., hk , . . -
.
e
h1 (e), ..., hk (e).
, h1 (e), ..., hk (e). , . , .
5.3.1
- , - , m . , - -,
:
1
1
.
m
5.
137
, -, :
1
1
m
k
.
n , , :
nk
1
.
1
m
, :
nk
1
1 1
.
m
, . :
f=
nk !k
k
1
= 1 enk/m ,
1 1
m
1 . ,
m n .
, k -, m n,
f k. f
:
nk/m
)
f = ek ln(1e
.
g = k ln(1 enk/m ). :
g
nk enk/m
= ln(1 enk/m ) +
k
m 1 enk/m
g k = ln 2 (m/n) ' 0.6931 m
n . f = (1/2)k ' 0.6185m/n .
5.3.2
1+
1 x
x
=e
5.
138
19
29
:
1
11
5.4
B-
B- , , .
.
B- - , -. , B- , B- .
B-, - , O(lg n),
, - , .
5.4.1
B-
B- t , :
1. 2t .
2. , , t .
3. , .
4. , h.
5. k k 1 .
5.
139
. ,
. , 2t 1 .
5.4.2
, t 1 . ,
, ,
.
open Batteries
2
17
22
27
32
37
let s pl it _ at _c e nt e r list =
let center = ( List . length list ) / 2 in
let left , right = List . split_at center list in
let middle , right = List . hd right , List . tl right in
left , middle , right
42
47
5.
140
62
67
72
77
82
87
5.5
-, , , , . , ,
.
- ,
-, / .
,
. - .
-
(static hash tables), , , .
-,
5.
141
(extendible hashing).
:
1. . 2,
.
2. :
, .
3. - h k , k
(, 32).
d, . , n = 2d
d k.
m, , , -,
B.
, .
key
1. seq = h(key).
2. d .
3. d seq. i , .
4. B i- .
5. bkey, m seq,
(d + 1).
6. B bkey,
.
(key, data)
1. B, i.
2. B , (key, data) B.
.
3. , m < d, .
:
(a) .
(b) , B, ,
(d + m + 1)- -.
- B, .
5.
142
(c) B: m = m + 1.
(d) , ,
B, B
d + m- -.
4. m = d, d.
. .
5. .
key
1. , key.
2. , .
3. .
4.
2m , :
(a) Q.
(b) . , ,
, .
(c) m = m 1 .
(d) .
(e) Q.
5. , :
(a) .
(b) .
[1] . , . , . , . , : . , 2- ., 2005.
[2] . -, . . , . , : .
, 2003.
[3] C. Okasaki, Purely functional data structures. Cambridge University Press, 1999.
[4] C. Okasaki, Red-black tree in a functional setting. Journal of Functional Programming,
Volume 9 Issue 4, July 1999.
[5] A. Broder, M. Metzenmacher, Network applications of Bloom filters: a survey. 2005.
[6] R. Fagin, J. Hievergelt, N. Peppenger, H. Raymond Strong, Extendible hashing a fast access
method for dynamic files. ACM Transactions on Database Systems 4 (3): 315344, 1979.
143
Common Lisp
, ,
:
;
;
;
;
;
;
( !);
, CLOS ;
.
6.1
DEFUN. :
( defun function-name ( parameter *)
" Optional documentation string "
body *)
, , .
.
,
, . , , , (keyword) .
, . , , ( ) DOCUMENTATION.
144
6. COMMON LISP
145
DEFUN CL. , , .
RETURN-FROM.
( defun verbose-sum ( x y )
" Sum any two numbers after printing a message . "
( format t " Summing ~ d and ~ d .~% " x y )
(+ x y ) ) ( defun foo ()
5
( documentation verbose-sum function ) = > " Sum any two numbers after printing
a message . "
6.1.1
.
( ), . ,
.
.
, , CL .
. .
( defun foo ( a b & optional c d )
( list a b c d ) )
4
( foo 1 2)
= > (1 2 NIL NIL )
( foo 1 2 3)
= > (1 2 3 NIL )
( foo 1 2 3 4) = > (1 2 3 4)
,
NIL.
, . , .
( defun foo ( a & optional ( b 10) )
( list a b ) )
( foo 1 2) = > (1 2)
( foo 1)
= > (1 10)
, , , .
( defun make -recta ngle ( width & optional ( height width ) )
...)
,
. , , .
6. COMMON LISP
146
T,
, NIL
.
( defun foo ( a b & optional ( c 3 c-supplied-p ) )
( list a b c c-supplied-p ) )
( foo 1 2)
= > (1 2 3 NIL )
( foo 1 2 3) = > (1 2 3 T )
( foo 1 2 4) = > (1 2 4 T )
(rest)
,
, .
, .
( defun + (& rest numbers ) ...)
, , ,
, &key
.
( defun foo (& key a b c )
( list a b c ) )
10
( foo )
( foo : a
( foo : b
( foo : c
( foo : a
( foo : a
( foo : a
=>
1)
=>
1)
=>
1)
=>
1 : c 3)
=>
1 : b 2 : c 3) = >
1 : c 3 : b 2) = >
, supplied-p-.
, ,
, .
( defun foo (& key ( a 0) ( b 0 b-supplied-p ) ( c (+ a b ) ) )
( list a b c b-supplied-p ) )
( foo
( foo
( foo
( foo
:a
:b
:b
:a
1)
1)
1 : c 4)
2 : b 1 : c 4)
=>
=>
=>
=>
(1
(0
(0
(2
0
1
1
1
1
1
4
4
NIL )
T)
T)
T)
, , , ,
, , .
( defun foo (& key ((: apple a ) ) ((: box b ) 0) ((: charlie c ) 0 c-supplied-p ) )
( list a b c c-supplied-p ) )
3
6. COMMON LISP
147
,
. ,
, : , , , .
, , . .
.
1
11
( foo : a 1 : b 2 : c 3)
6.1.2
= > ((: A 1 : B 2 : C 3) 1 2 3)
, . .
RETURN-FROM,
.
( defun foo ( n )
( dotimes ( i 10)
( dotimes ( j 10)
( when ( > (* i j ) n )
( return-from foo ( list i j ) ) ) ) ) )
6.1.3
CL . DEFUN :
1. -.
2. , -.
- FUNCTION #.
( defun foo ( x ) (* 2 x ) )
( function foo ) = > # < FUNCTION FOO >
# foo
= > # < FUNCTION FOO >
- , FUNCALL APPLY. , , .
FUNCALL , , ,
6. COMMON LISP
148
. FUNCALL -,
- .
FUNCALL. -
, , min max step.
( defun plot ( fn min max step )
( loop for i from min to max by step do
( loop repeat ( funcall fn i ) do ( format t " * " ) )
( format t " ~% " ) ) )
5
10
15
APPLY -,
. APPLY - .
( apply # plot (# exp 0 4 1/2) )
( apply # plot # exp (0 4 1/2) )
6.1.4
LAMBDA.
( lambda ( parameters ) body )
( funcall # ( lambda ( x y ) (+ x y ) ) 2 3) = > 5
(( lambda ( x y ) (+ x y ) ) 2 3)
=> 5
6.2
CL : ().
CL . ,
,
.
, , LET.
:
( let ( variable *)
body-form *)
variable ,
, ( NIL).
( let (( x 10) ( y 20) z )
( list x y z ) )
6. COMMON LISP
149
, .
. body-form*.
10
15
( defun foo ( x )
( format t " Parameter : ~ a ~% " x )
( let (( x 2) )
( format t " External LET : ~ a ~% " x )
( let (( x 3) )
( format t " Internal LET : ~ a ~% " x ) )
( format t " External LET : ~ a ~% " x ) )
( format t " Parameter : ~ a ~% " x ) )
CL-USER > ( foo
Parameter : 1
External LET :
Internal LET :
External LET :
Parameter : 1
NIL
1)
2
3
2
LET: LET*. ,
LET LET, LET*
, .
6.2.1
10
( let (( count
( list
# ( lambda
# ( lambda
# ( lambda
( funcall
( funcall
( funcall
( funcall
0) )
() ( incf count ) )
() ( decf count ) )
() count ) ) )
( first * count-fns *) )
( first * count-fns *) )
( second * count-fns *) )
( third * count-fns *) )
=>
=>
=>
=>
1
2
1
1
(closure), , LET. , . ,
, .
6.2.2
()
CL : DEFVAR DEFPARAMETER.
, DEFVAR ,
DEFPARAMETER . ,
.
, .
( defvar
* count *
( defvar
* count *
( defparameter * count * 2)
* count * = > 2
6. COMMON LISP
150
DEFVAR . (unbound).
-
, , , , ,
( ).
( defun hello-world ()
( format * st a nd ar d -o ut p ut * " Hello , world !~% " ) )
10
/tmp/scream.txt :
1
(). , , ,
, . , .
6.2.3
DEFCONSTANT.
DEFCONSTANT DEFPARAMETER.
( defconstant name i n i t i a l - v a l u e - f o r m [ d o c u m e n t a t i o n - s t r i n g ])
.
.
6.2.4
, SETF, CL :
( setf place value )
SETF (expand) , place. place , SETQ,
, . SETF
.
( defvar * x *)
( defvar * y *)
6. COMMON LISP
151
. SETF
(place). CL , , .
( let (( x 1) )
( setf x 10)
x ) = > 10
5
10
15
( let (( x (2 2 3) ) )
( setf ( first x ) 1)
x ) = > (1 2 3)
( let (( x #(2 2 3) ) )
( setf ( aref x 0) 1)
x ) = > #(1 2 3)
( let (( x ( m ak e -h as h -t a bl e ) ) )
( setf ( gethash key x ) 10)
( gethash key x ) ) = > 10
DEFSETF DEFINE-SETF-EXPANDER.
6.3
, S-
CL.
- (embedded domain-specific languages).
Lisp , Lisp,
, , , ,
, , Lisp,
.
,
. ,
, , , . :
, . , , ,
.
, WHEN :
( defmacro when ( condition & rest body )
( if , condition ( progn , @body ) ) )
, FOO:
( defun foo ( x )
( when ( > x 10) ( print big ) ) )
DEFMACRO :
6. COMMON LISP
152
6.3.1
.
.
-. .
, &body &rest. &body &rest .
Listing 6.1:
( defun primep ( number )
( when ( > number 1)
( loop for fac from 2 to ( isqrt number ) never ( zerop ( mod number fac ) ) ) ) )
5
10
6.3.2
,
() , ,
at (@).
. at ,
, .
, . ,
, .
6.1:
(a
(a
(a
(a
(a
(list a (+ 1 2) c)
(list a (+ 1 2) c)
(list a (list 1 2) c)
(list a (list 1 2) c)
(append (list a) (list 1 2))
(a
(a
(a
(a
(a
(+ 1 2) c)
,(+ 1 2) c)
(list 1 2) c)
,(list 1 2) c)
,@(list 1 2))
(+ 1 2) c)
3 c)
(list 1 2) c)
(1 2) c)
1 2 c)
: MACROEXPAND-1
MACROEXPAND-1 -
MACROEXPAND.
6. COMMON LISP
153
. MACROEXPAND .
6.3.3
.
, DO-PRIMES (random 100):
( do-primes ( p 0 ( random 100) )
( format t " ~ d " p ) )
MACROEXPAND-1, , (random
DO:
100)
end
.
.
, ,
, end, ,
start. .
DO
ending-value. ,
.
do-primes - :
( do-primes ( ending-value 0 10)
( print ending-value ) )
MACROEXPAND-1 :
( do (( ending-value ( next-prime 0) ( next-prime (1+ ending-value ) ) )
( ending-value 10) )
(( > ending-value ending-value ) )
( print ending-value ) )
. GENSYM .
- . , GENSYM, .
6. COMMON LISP
154
6.3.4
GENSYM:
DO-PRIMES, .
( defmacro with-gensyms ((& rest names ) & body body )
( let ,( loop for n in names collect ( , n ( gensym ) ) )
, @body ) )
, loop-:
CL-USER > ( loop for n in ( a b c ) collect ( , n ( gensym ) ) )
(( A ( GENSYM ) ) ( B ( GENSYM ) ) ( C ( GENSYM ) ) )
6.4
6.4.1
CL :
, -;
;
;
;
.
:
CL-USER > ( list +1 -1 2/1 3/2 6/4 # xA # b01001 # b1010 /1011 # o777 #36 rABFG 1.)
(1 -1 2 3/2 3/2 10 9 10/11 511 481372 1)
6. COMMON LISP
155
, . , 10. #B #b,
. #O #o ,
#X #x .
( 2 36) #nR, n (
).
A-Z a-z.
:
CL-USER > ( list 1.0 1 e0 1 d0 0.1 .1 1 e-3 )
(1.0 1.0 1.0 d0 0.1 0.1 0.001)
: #C #c, , .
(+)
(+ 1 2 3)
(- 2)
(*)
(/ 10 5 2)
=>
=>
=>
=>
=>
0
6
-2
1
1
(+
(((*
(/
1 2)
5 4)
10 3 5)
2 3 4)
2 3)
=>
=>
=>
=>
=>
3
1
2
24
2/3
(+ # c (1 2) 3) = > # c (4 2)
CL
( ) :
1. FLOOR ,
, .
2. CEILING ,
, .
3. TRUNCATE , FLOOR , CEILING .
4. ROUND .
,
.
MOD REM .
FLOOR TRUNCATE :
(+ (* ( floor
(/ x y ) ) y ) ( mod x y ) ) == x
(+ (* ( truncate (/ x y ) ) y ) ( rem x y ) ) == x
6. COMMON LISP
156
= ,
, . <, >, <= >=
.
(= 1 1.0 # c (1.0 0.0) # c (1 0) )
(/= 1 1)
= > NIL
(/= 1 2 3)
=> T
( <= 2 3 3 4) = > T
=> T
(/= 1 2)
=> T
(/= 1 2 3 1.0) = > NIL
( <= 2 3 4 3)
= > NIL
6.4.2
CL , . : #\, . #\ .
:
#\ .
Lisp, Space Newline. , Tab, Page, Rubout, Linefeed, Return
Backspace.
, , : CHAR=
, CHAR=/, CHAR<, CHAR>, CHAR<= CHAR>=. , ,
: CHAR-EQUAL, CHAR-NOT-EQUAL, CHAR-LESSP, CHAR-GREATERP, CHAR-NOT-GREATERP
CHAR-NOT-LESSP.
6.4.3
. ,
. , ,
(") (\).
.
, , : STRING=,
STRING=/, STRING<, STRING>, STRING<= STRING>=. , , : STRING-EQUAL, STRING-NOT-EQUAL, STRING-LESSP, STRING-GREATERP, STRINGNOT-GREATERP STRING-NOT-LESSP. ,
.
: :start1, :end1, :start2
:end2.
( string = " foobarbaz " " quuxbarfoo " : start1 3 : end1 6 : start2 4 : end2 7) = > T
6.5
CL : -. : , .
,
, , .
6. COMMON LISP
6.5.1
157
. .
VECTOR #(...). , , , .
( vector )
= > #()
( vector 1)
= > #(1)
( vector 1 2) = > #(1 2)
MAKE-ARRAY . , ,
. . .
:initial-element , .
( make-array 5 : i n it ia l -e l em en t nil ) = > #( NIL NIL NIL NIL NIL )
(fill pointer).
:fill-pointer.
( make-array 5 : fill-pointer 0) = > #()
( make-array 5 : fill-pointer 3) = > #(0 0 0)
( make-array 5 : fill-pointer 3 : in it i al -e l em e nt nil ) = > #( NIL NIL NIL )
:adjustable.
, 5 ,
.
( make-array 5 : fill-pointer 0 : adjustable t ) == > #()
.
, , :
element-type.
( make-array 5 : fill-pointer 0 : adjustable t : element-type character ) = > " "
( make-array 3 : i n i t i a l - c o n t e n t s (0 1 0) : element-type bit ) = > #*010
6.5.2
6. COMMON LISP
158
6.2:
COUNT
FIND
POSITION
REMOVE
NIL
NIL
,
,
SUBSTITUTE
6.3:
:test
, ( , :key) .
, . NIL
.
()
.
(n 1) . NIL .
, .
, , NIL
( REMOVE SUBSTITUTE).
EQL
:key
:start
:end
:from-end
:count
NIL
0
NIL
NIL
NIL
Listing 6.2:
( length #(1 2 3) )
( elt 1 #(1 2 3) )
( count 1 #(1 2 1 2 3 1 2 3 4) )
( remove 1 #(1 2 1 2 3 1 2 3 4) )
( remove 1 (1 2 1 2 3 1 2 3 4) )
( remove #\ a " foobarbaz " )
( substitute 10 1 #(1 2 1 2 3 1 2 3 4) )
( substitute 10 1 (1 2 1 2 3 1 2 3 4) )
( substitute #\ x #\ b " foobarbaz " )
( find 1 #(1 2 1 2 3 1 2 3 4) )
( find 10 #(1 2 1 2 3 1 2 3 4) )
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
=>
3
2
3
#(2 2 3 2 3 4)
(2 2 3 2 3 4)
" foobrbz "
#(10 2 10 2 3 10 2 3 4)
(10 2 10 2 3 10 2 3 4)
" fooxarxaz "
1
NIL
6. COMMON LISP
13
( position 2 #(1 2 1 2 3 1 2 3 4) )
( position 9 #(1 2 1 2 3 1 2 3 4) )
159
=> 1
= > NIL
( count " foo " #( " foo " " bar " " baz " ) : test # string =)
=> 1
( find c #(( a 10) ( b 20) ( c 30) ( d 40) ) : key # first ) = > ( C 30)
18
CL , , , ,
. ,
, -IF. , , , - .
, -IF-NOT,
, .
Listing 6.3:
( count-if # evenp #(1 2 3 4 5) )
=> 2
( count-if-not # evenp #(1 2 3 4 5) )
=> 3
( position-if # digit-char-p " abcd0001 " ) = > 4
5
10
( remove-if-not # alpha-char-p
#( " foo " " bar " " 1 baz " ) : key # ( lambda ( x ) ( elt x 0) ) ) = > #( " foo " " bar " )
6.5.3
6. COMMON LISP
160
Listing 6.4: -
( defparameter * h * ( m a ke -h a sh- ta bl e ) )
( setf ( gethash key1 * h *) value1 )
( setf ( gethash key2 * h *) value2 )
5
10
6.6
CL ,
, .
.
6.6.1
Cons-
CAR CDR,
.
6.6.2
LIST. APPEND ,
.
( defparameter * list-1 * ( list 1 2) )
( defparameter * list-2 * ( list 3 4) )
( defparameter * list-3 * ( append * list-1 * * list-2 *) )
5
6. COMMON LISP
161
NCONC , , cons-
, .
CL SECOND TENTH, .
NTH : , n-
( ) . NTHCDR,
n- REST .
28 CAR/CDR .
4 A D C R. A
CAR, D CDR.
6.4:
LAST
cons- . n, n .
cons-.
n, n .
BUTLAST, ,
.
cons-.
T, cons-,
.
, , CDR cons- , LIST APPEND.
n . NIL
:initial-element.
REVERSE APPEND: ,
REVERSE . .
; ,
NREVERSE . .
, cons-.
, cons-.
, cons- NIL
, NIL.
BUTLAST
NBUTLAST
LDIFF
TAILP
LIST*
MAKE-LIST
REVAPPEND
NRECONC
CONSP
ATOM
LISTP
NULL
6.6.3
6. COMMON LISP
162
6.6.4
, ,, ,
. , ((nil1nil)2(nil3nil))
,
2, 1 3.
CL .
COPY-TREE, , COPY-LIST, , .
TREE-EQUAL , ,
.
SUBST . SUBSTIF, NSUBST NSUBST-IF .
( subst 10 1 (1 2 (3 2 1) ((1 1) (2 2) ) ) ) = > (10 2 (3 2 10) ((10 10) (2 2) ) )
Listing 6.5:
14
19
24
29
6. COMMON LISP
163
(9) ) ) ) )
34
( defun show ( t r a v e r s a l - f u n c t i o n )
( format t " ~&~(~ A ~) :~12 ,0 T " t r a v e r s a l - f u n c t i o n )
( funcall t r a v e r s a l - f u n c t i o n * tree * ( lambda ( value ) ( format t " ~ A " value ) ) )
)
( map nil # show ( preorder inorder postorder level-order ) )
preorder :
inorder :
postorder :
level - order :
6.6.5
1
7
7
1
2
4
4
2
4
2
2
3
7
5
5
4
5
1
1
5
3
8
8
6
6
6
6
7
8
9
9
8
9
3
3
9
CL , . ADJOIN PUSHNEW.
( defparameter * set * () )
( adjoin 1 * set *)
* set * = > NIL
5
6.6.6
, , . /, ,
, .
, ,
cons-.
(( a . 1) ( b . 2) ( c . 3) )
( assoc c (( a . 1) ( b . 2) ( c . 3) ) ) = > 3
( assoc d (( a . 1) ( b . 2) ( c . 3) ) ) = > NIL
( cdr ( assoc a (( a . 1) ( b . 2) ( c . 3) ) ) ) = > 1
( assoc " a " (( " a " . 1) ( " b " . 2) ( " c " . 3) ) : test # string =) = > ( " a " . 1)
( assoc a (( a . 10) ( a . 1) ( b . 2) ( c . 3) ) ) = > ( A . 10)
6. COMMON LISP
164
COPY-ALIST.
PAIRLIS,
.
6.6.7
Destructuring-bind
DESTRUCTURING-BIND
.
( d e s t r u c t u r i n g - b i n d ( parameter *) list
body-form *)
Listing 6.6:
( d e s t r u c t u r i n g - b i n d ( x y z ) ( list 1 2 3)
( list : x x : y y : z z ) ) = > (: X 1 : Y 2 : Z 3)
3
13
18
23
6.7
Loop
;
, , , ;
Lisp;
6. COMMON LISP
165
;
;
;
.
6.7.1
LOOP (clause), .
:
, ,
. ,
(prepositions), , from to.
, . ,
return, go throw. :
,
.
initially progn.
.
finally.
:
6. COMMON LISP
166
for as .
, , , ,
. , and,
.
with let. for,
with .
. - .
collect , , . ,
.
append , , . , (. APPEND).
nconc , , . , (. nconc).
sum ,
. ,
.
count , . , .
minimize . ,
.
maximize . ,
.
loop-finish , . finally, .
for as , .
repeat .
while , . (if (not condition)(loop-finish)).
until , . (if condition (loop-finish)).
always , , NIL. , T
.
6. COMMON LISP
167
never ,
, NIL. , T
.
thereis ,
, .
do .
return , . do (return value).
if , ,
. , ;
and.
when if.
unless , when,
, .
else if, when
unless.
,
else.
end .
named loop.
, initially,
.
, finally, . finally.
LOOP
. .
. - .
. .
, .
:
return.
RETURN, RETURN-FROM .
6. COMMON LISP
168
LOOP :
6.7.2
for- :
;
;
, cons-;
, , : ;
- -;
;
.
loop for-, ,
.
( loop
for item in (1 2 3)
for i from 1 to 4
collect i )
= > (1 2 3)
Listing 6.7:
1
( loop
( loop
( loop
( loop
( loop
=>
=>
=>
=>
=>
(0 1 2 3)
(-1 -2 -3)
(1 2 3)
(2 2 0)
(0 2 4)
6. COMMON LISP
169
( loop
( loop
( loop
( loop
( loop
for
for
for
for
for
i
i
x
x
x
- , - , .
:
( loop for var being the things in ha sh - or - pa ck a ge ...)
( length ( loop for s being the symbol in : cl-user collect s ) ) = > 1277
Equals-then
, , for ,
- , equals-then.
( loop for var = i n i t i a l - v a l u e - f o r m [ then step-form ] ...)
10
( loop repeat 5
for y = 1 then (+ x y )
for x = 0 then y
collect y ) = > (1 1 2 4 8)
( loop repeat 5
for x = 0 then y
and y = 1 then (+ x y )
collect y ) = > (1 1 2 3 5)
LOOP .
( loop for ( a b ) in ((1 2) (3 4) (5 6) )
append ( list a b ) )
= > (1 2 3 4 5 6)
6. COMMON LISP
170
do ( doing).
( loop for i from 1 to 10 do ( print i ) )
do, , ,
RETURN-FROM.
RETURN
( block outer
( loop for i from 0 return 100)
( print " This will print " )
200) = > 200
5
( block outer
( loop for i from 0 do ( return-from outer 100) )
( print " This won t print " )
200) = > 100
do , , , IF
WHEN .
( loop for i from 1 to 10 do ( when ( evenp i ) ( print i ) ) )
do , , ,
, - , :
( loop for i from 1 to 10 when ( evenp i ) sum i ) = > 30
, . ,
it.
( loop for key in some-list when ( gethash key some-hash ) collect it )
else-. and. , , :
( loop for i from 1 to 100
if ( evenp i )
minimize i into min-even and
maximize i into max-even and
6. COMMON LISP
171
10
15
20
6.8
Format
FORMAT (). ,
( loop for cons on list
do ( format t " ~ a " ( car cons ) )
when ( cdr cons ) do ( format t " , " ) )
( format t " ~{~ a ~^ , ~} " list )
FORMAT : ,
. :
T *STANDARD-OUTPUT*.
NIL. FORMAT .
, .
. .
6.8.1
(~) ( ),
. (
).
, , ,
.
:
v FORMAT
.
# .
6. COMMON LISP
( format
( format
( format
( format
( format
nil
nil
nil
nil
nil
" ~ $ " pi )
" ~5 $ " pi )
" ~ v$ " 3 pi )
" ~# $ " pi )
" ~ ,5 f " pi )
=>
=>
=>
=>
=>
172
3.14
3.14159
3.142
3.1
3.14159
@, .
( format
( format
( format
( format
nil
nil
nil
nil
=>
=>
=>
=>
1000000
1 ,000 ,000
+1000000
+1 ,000 ,000
~A . ~S
,
READ.
( format nil " The value is : ~ a " 10)
= > " The value is : 10 "
( format nil " The value is : ~ a " " foo " )
= > " The value is : foo "
( format nil " The value is : ~ a " ( list 1 2 3) ) = > " The value is : (1 2 3) "
~% ~& , ~% ,
~& .
( format
( format
( format
( format
nil
nil
nil
nil
" ~ c " #\ a )
" ~: c " #\ Space )
" ~ @c ~% " #\ a )
" ~: @c " ( code-char 0) )
=>
=>
=>
=>
"a"
" Space "
" #\ a "
" ^ @ ( Control @ ) "
( format nil " ~4 , 0 d- ~2 , 0 d- ~2 , 0 d " 2005 6 10) = > " 2005-06-10 "
( format nil " ~: d " 100000000)
= > " 100 ,000 ,000 "
( format nil " ~ , , . ,4: d " 100000000) = > " 1.0000.0000 "
15
( format
( format
( format
( format
nil
nil
nil
nil
~F , , , . ~F ,
. ~E, , .
( format
( format
( format
( format
5
nil
nil
nil
nil
" ~ f " pi )
" ~ ,4 f " pi )
" ~ e " pi )
" ~ ,4 e " pi )
=>
=>
=>
=>
" 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 d0 "
" 3.1416 "
" 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 d +0 "
" 3.1416 d +0 "
6. COMMON LISP
173
~R
.
( format
( format
( format
( format
nil
nil
nil
nil
=>
=>
=>
=>
~P s, 1.
( format nil " file ~ p " 1) = > " file "
( format nil " file ~ p " 10) = > " files "
( format nil " file ~ p " 0) = > " files "
5
10
~(
( format nil " ~ r file ~: p " 1) = > " one file "
( format nil " ~ r file ~: p " 10) = > " ten files "
( format nil " ~ r file ~: p " 0) = > " zero files "
( format nil " ~ r famil ~: @p " 1) = > " one family "
( format nil " ~ r famil ~: @p " 10) = > " ten families "
( format nil " ~ r famil ~: @p " 0) = > " zero families "
~).
( format
( format
( format
( format
6.8.2
nil
nil
nil
nil
=>
=>
=>
=>
~[ ~], , ~;. ~[ ,
FORMAT. , .
( format
( format
( format
( format
nil
nil
nil
nil
0)
1)
2)
3)
=>
=>
=>
=>
~:; ~;, .
( format nil " ~[ zero ~; one ~; two ~:; many ~] " 3)
~[ .
,
NIL, .
( format t " ~:[ FAIL ~; pass ~] " test-result )
6. COMMON LISP
6.8.3
174
~{ FORMAT .
( format nil " ~{~ a , ~} " ( list 1 2 3) )
=> "1,2,3,"
( format nil " ~{~ a ~^ , ~} " ( list 1 2 3) ) = > " 1 , 2 , 3 "
( format nil " ~ @ {~ a ~^ , ~} " 1 2 3)
=> "1,2,3"
.
( , ~@{) ,
~:{.
6.8.4
~* .
. ( ),
.
( format nil " ~ r ~:*(~ d ) " 1) = > " one (1) "
~{ ~* .
( format nil " ~{~ s ~*~^ ~} " (: a 10 : b 20) ) = > " : A : B "
~* .
, , . @
, ,
( 0).
6.9
CLOS
6.9.1
( ),
, .
6. COMMON LISP
175
bank-account
checking-account
savings-account
. 6.1:
DEFGENERIC DEFUN, , .
DEFGENERIC ,
, .
( defgeneric withdraw ( account amount )
(: documentation " Withdraw the specified amount from the account .
Signal an error if the current balance is less than amount . " ) )
( ) , . :
( EQL).
, (&rest)
(&key, &allow-other-keys) , .
, . ,
, .
( defmethod withdraw (( account bank-account ) amount )
( when ( < ( balance account ) amount )
( error " Account overdrawn . " ) )
( decf ( balance account ) amount ) )
CALL-NEXT-METHOD
. ,
, , bank-account.
, ,
.
, .
, EQL-,
, DEFMETHOD.
Listing 6.8: EQL-
6. COMMON LISP
6.9.2
176
,
. :
1. , .
2. . (
:argument-precedence-order DEFGENERIC).
.
3. ,
.
, , . , , . , checking-account
, ,
bank-account.
EQL- , . EQL ,
EQL-.
.
, . . ,
, ,
CALL-NEXT-METHOD.
( , , ).
: :before, :after :around. :
( defmethod withdraw : before (( account bank-account ) amount ) ...)
. :before ( ) .
, .
:after , . :around ,
.
:
6. COMMON LISP
177
:around , .
.
:around CALL-NEXT-METHOD.
, - . CALL-NEXTMETHOD, , NO-NEXT-METHOD.
NEXT-METHOD-P ,
.
:around CALL-NEXT-METHOD, :
around . :around
:around ,
:
:before , . . CALL-NEXT-METHOD
.
. CALL-NEXT-METHOD . ,
- . CALL-NEXT-METHOD, , NO-NEXT-METHOD. NEXT-METHOD-P ,
. CALL-NEXT-METHOD ,
.
:after , . . CALL-NEXT-METHOD
.
:around , , . CALL-NEXT-METHOD,
:around ,
.
, , .
Listing 6.9:
; ;; integer = > rational = > real = > number = > t
( defgeneric speak ( arg ) )
10
15
6. COMMON LISP
178
25
30
35
40
CL 9 : +, and, append, list,
progn. :
, ,
,
. :around .
, , + ,
, . , , and or ,
, .
, , .
, :method-combination .
max, min, nconc, or
Listing 6.10:
( defgeneric priority ( job )
(: documentation " Return the priority at which the job should be run . " )
(: m e t h o d - c o m b i n a t i o n + : m o s t - s p e c i f i c - l a s t ) )
5
. :
:around . , :around
. CALL-NEXT-METHOD NO-NEXT-METHOD-P.
, . CALL-NEXT-METHOD NO-NEXTMETHOD-P.
6. COMMON LISP
179
, DEFINE-METHOD-COMBINATION
.
6.9.3
, T.
: . , , INTEGER, STRING LIST.
, , .
DEFCLASS. DEFCLASS
, .
: , (
).
( defclass name ( d i r e c t - s u p e r c l a s s - n a m e *)
( sl ot-spe cifier *) )
,
. MAKE-INSTANCE.
, STANDARD-OBJECT.
STANDARD-OBJECT T.
( defclass bank-account () ...)
( defclass c h e c k i n g - a c c o u n t ( bank-account ) ...)
( defclass s av i ng s- a cc ou n t ( bank-account ) ...)
6.9.4
DEFCLASS . .
SLOT-VALUE SETF
SLOT-VALUE.
.
.
( defclass bank-account ()
( customer-name
balance ) )
5
6.9.5
.
:initarg ,
MAKE-INSTANCE. :initform , , MAKE-INSTANCE
:initarg.
( defclass bank-account ()
(( customer-name
: initarg : customer-name )
6. COMMON LISP
180
( balance
: initarg : balance
: initform 0) ) )
( defparameter * account *
( make-instance bank-account : customer-name " John Doe " : balance 1000) )
10
15
:initarg :initform .
( defvar * ac c ou nt - nu m be rs * 0)
10
( defclass bank-account ()
(( customer-name
: initarg : customer-name
: initform ( error " Must supply a customer name . " ) )
( balance
: initarg : balance
: initform 0)
( ac count- number
: initform ( incf * a cc ou n t- nu m be rs *) ) ) )
10
15
20
25
30
( defclass bank-account ()
(( customer-name
: initarg : customer-name
: initform ( error " Must supply a customer name . " ) )
( balance
: initarg : balance
: initform 0)
( ac count- number
: initform ( incf * a cc ou n t- nu m be rs *) )
account-type ) )
( defmethod i n i t i a l i z e - i n s t a n c e : after (( account bank-account )
& key o p e n i n g - b o n u s - p e r c e n t a g e )
( when o p e n i n g - b o n u s - p e r c e n t a g e
( incf ( slot-value account balance )
(* ( slot-value account balance ) (/ o p e n i n g - b o n u s - p e r c e n t a g e 100) ) )
)
( let (( balance ( slot-value account balance ) ) )
( setf ( slot-value account account-type )
( cond
(( >= balance 100000) : gold )
(( >= balance 50000) : silver )
( t : bronze ) ) ) ) )
( defparameter * acct * ( make-instance
bank-account
: customer-name " Sally Sue "
: balance 1000
: o p e n i n g - b o n u s - p e r c e n t a g e 5) )
( slot-value * acct * balance ) = > 1050
6. COMMON LISP
6.9.6
181
SLOT-VALUE . ,
, , .
:reader ,
. DEFCLASS , , , , . ,
( balance
: initarg : balance
: initform 0
: reader balance )
:
1
:writer . SETF-,
, .
( customer-name
: initarg : customer-name
: initform ( error " Must supply a customer name . " )
: reader customer-name
: writer ( setf customer-name ) )
, :accessor.
( customer-name
: initarg : customer-name
: initform ( error " Must supply a customer name . " )
: accessor customer-name )
:
1
11
( defclass bank-account ()
(( customer-name
: initarg : customer-name
: initform ( error " Must supply a customer name . " )
: accessor customer-name
: documentation " Customer s name " )
( balance
: initarg : balance
: initform 0
: reader balance
: documentation " Current account balance " )
( ac count- number
: initform ( incf * a cc ou n t- nu m be rs *)
: reader acc ount-n umber
: documentation " Account number , unique within a bank . " )
6. COMMON LISP
182
( account-type
: reader account-type
: documentation " Type of account , one of : gold , : silver , or : bronze . " ) ) )
16
CL : WITH-SLOTS
WITH-ACCESSORS.
( with-slots ( slot *) instance-form
body-form *)
slot ,
, , ,
, .
, SLOTVALUE . :
( defmethod a s s e s s - l o w - b a l a n c e - p e n a l t y (( account bank-account ) )
( when ( < ( slot-value account balance ) * m in im u m- ba l an ce *)
( decf ( slot-value account balance ) (* ( slot-value account balance ) .01)
)))
5
:accessor, WITH-ACCESSORS, ,
SLOT-VALUE.
( defmethod a s s e s s - l o w - b a l a n c e - p e n a l t y (( account bank-account ) )
( wi th-acc essors (( balance balance ) ) account
( when ( < balance * m in i mu m -b al a nc e *)
( decf balance (* balance .01) ) ) ) )
6.9.7
, , :allocation.
:instance ( ), :class. , .
. ,
, .
6.9.8
CL . ,
.
. .
,
:initform, .
:initarg , .
6. COMMON LISP
183
6.9.9
, . CL ,
DEFCLASS: , ,
, , . ,
( defclass m o n e y - m a r k e t - a c c o u n t ( c h e c k i n g - a c c o u n t s av in g s- ac c ou n t ) () )
( money-market-account
checking-account
s av in g s- a cc ou n t
bank-account
s ta nd a rd - ob je c t
t)
, ,
money-market-account bank-account.
6.10
, :
(property list). , .
. , .
. , .
. ,
. ,
.
6.10.1
,
(property list, plist). ,
6. COMMON LISP
184
( ), , , , ( ).
.
. , .
SYMBOL-PLIST.
GET GETF SETF. :
( defun get ( symbol indicator & optional default ) ...)
( defun getf ( place indicator & optional default ) ...)
( get x y ) == ( getf ( symbol-plist x ) y )
Listing 6.11:
( defvar foo ( list : bar t : baz 3 : hunoz " Huh ? " ) )
2
GET-PROPERTIES .
( defun get- proper ties ( place indica tor-li st ) ...)
REMPROP REMF.
( defun remprop ( symbol indicator ) ...)
( defun remf ( place indicator ) ...)
( remprop x y ) == ( remf ( symbol-plist x ) y )
Listing 6.12:
( defvar foo ( list color blue height 6.3 near-to bar ) )
2
6.10.2
.
SYMBOL-NAME.
( symbol-name xyz ) = > " XYZ "
6.10.3
.
, , .
. , READ
, .
, .
#:.
INTERN. MAKE-SYMBOL
. COPY-SYMBOL
6. COMMON LISP
185
. .
.
( defun make-symbol ( print-name ) ...)
( defun copy-symbol ( sym & optional copy-props ) ...)
GENSYM .
( defun gensym (& optional x ) ...)
*GENSYM-COUNTER*
X, ( ). G
X, ( ).
( gensym ) = > G7
( gensym " FOO- " ) = > FOO-8
( gensym 32) = > FOO-32
( gensym ) = > FOO-33
, , SYMBOL-PACKAGE.
, KEYWORD. , . ,
, KEYWORDP.
( keywordp : sym ) = > T
( eql : foo : foo ) = > T
6.11
. FIND-PACKAGE .
FIND-SYMBOL. ,
, , *PACKAGE*,
.
READ - , INTERN. ,
.
, package:symbol
package::symbol. package, .
, . ,
FIND-SYMBOL, .
. , . , .
, .
, , .
, ,
. .
.
.
. ,
.
6. COMMON LISP
6.11.1
186
( defpackage : email-app
(: use : common-lisp : db : network )
(: shadow : build-index )
(: s h a d o w i n g - i m p o r t - f r o m : network : save )
(: import-from : email : p a r s e - e m a i l - a d d r e s s )
(: export : make-email
: send-email
: save-email )
(: nicknames : eapp ) )
:use . :shadow
, :use.
, ,
:use. :shadowing-import-from ,
, . :export .
:nicknames .
.
:
1. :shadow :shadowing-import-from
2. :use
3. :import-from :intern
4. :export
6.12
CL , . ; , , .
CL , (), , ,
.
, , ( ) CONDITION. STANDARD-OBJECT.
, DEFCLASS, .
, SLOT-VALUE, :reader :accessor.
INITIALIZE-INSTANCE.
MAKE-CONDITION ( MAKE-INSTANCE).
ERROR.
( d e f i n e - c o n d i t i o n m a l f o r m e d - l o g - e n t r y - e r r o r ( error )
(( text : initarg : text : reader text ) ) )
6.12.1
, . -
,
. ERROR,
6. COMMON LISP
187
SIGNAL.
, . ERROR ,
.
( defun p a rs e- l og -e n tr y ( text )
( if ( w e l l - f o r m e d - l o g - e n t r y - p text )
( make-instance log-entry ...)
( error m a l f o r m e d - l o g - e n t r y - e r r o r : text text ) ) )
,
, .
.
, , .
.
, SIGNAL
, .
.
, , . HANDLER-CASE.
( handler-case expression
( co nditio n-type ([ var ]) code ) *)
expression , HANDLER .
, condition-type,
, HANDLER-CASE.
CASE. code
6.12.2
PARSE-LOG-FILE .
, , , , ,
.
, HANDLER-CASE RESTART
-CASE. RESTART-CASE HANDLER-CASE , , .
,
.
6. COMMON LISP
188
skip-log-entry. , PARSE-LOG-FILE
, ,
NIL.
. , .
( defun log-analyzer ()
( dolist ( log ( find-all-logs ) )
( analyze-log log ) ) )
5
HANDLER
. HANDLERCASE HANDLER-BIND .
INVOKE-RESTART.
-BIND.
( defun log-analyzer ()
( handler-bind (( m a l f o r m e d - l o g - e n t r y - e r r o r
# ( lambda ( c )
( in voke-r estart sk ip-log -entry ) ) ) )
( dolist ( log ( find-all-logs ) )
( analyze-log log ) ) ) )
INVOKE-RESTART , CONTROL-ERROR. ,
:
( lambda ( c )
( let (( restart ( find-restart skip- log-en try ) ) )
( when restart ( invo ke-res tart restart ) ) ) )
6.12.3
, - /
.
, INVOKE-RESTART.
10
( defun p a rs e- l og -e n tr y ( text )
( if ( w e l l - f o r m e d - l o g - e n t r y - p text )
( make-instance log-entry ...)
( restart-case ( error m a l f o r m e d - l o g - e n t r y - e r r o r : text text )
( use-value ( value ) value )
( reparse-entry ( fixed-text ) ( pa r se -l o g- e nt ry fixed-text ) ) ) ) )
( defun log-analyzer ()
( handler-bind (( m a l f o r m e d - l o g - e n t r y - e r r o r
# ( lambda ( c )
( use-value
( make-instance m a l f o r m e d - l o g - e n t r y : text ( text c ) ) ) ) )
)
( dolist ( log ( find-all-logs ) )
( analyze-log log ) ) ) )
6. COMMON LISP
6.12.4
189
, .
SIGNAL , ;
,
SIGNAL NIL.
ERROR SIGNAL. , HANDLER-CASE , SIGNAL . SIGNAL , ERROR
, *DEBUGGER-HOOK*. , ERROR
, , .
WARN , . WARN
SIGNAL, , WARN
, *ERROR-OUTPUT* NIL. WARN MUFFLE-WARNING,
. MUFFLE-WARNING
, CONTROL-ERROR,
.
10
15
20
25
( defun count-down ( x )
( do (( counter x (1- counter ) ) )
((= counter 0) done )
( when (= counter 1)
( warn " Almost done " ) )
( format t " ~&~ D ~% " counter ) ) )
CL-USER > ( count-down 3)
3
2
Warning : Almost done
1
DONE
( defun i g n o r e - w a r n i n g s - w h i l e - c o u n t i n g ( x )
( handler-bind (( warning # ignore -warni ng ) )
( count-down x ) ) )
( defun igno re-war ning ( condition )
( declare ( ignore condition ) )
( mu ffle-w arning ) )
CL-USER > ( i g n o r e - w a r n i n g s - w h i l e - c o u n t i n g 3)
3
2
1
DONE
6.13
6. COMMON LISP
190
Listing 6.13:
Listing 6.14:
12
17
22
27
32
37
42
47
6. COMMON LISP
52
57
62
67
(( d es-sys tem-li b
ramlib ieee )
( dw01
( dw02
( dw03
( dw04
( dw05
( dw06
( dw07
( dware
( gtech
( ramlib
( std-cell-lib
( synopsys ) ) )
* DEPENDENCY-GRAPH *
191
> ( t o p o l o g i c a l - s o r t * d e p e n d e n c y - g r a p h *)
( IEEE DWARE DW02 DW05 DW06 DW07 GTECH DW01 DW04 STD-CELL-LIB SYNOPSYS STD
DW03 RAMLIB D ES-SYS TEM-LI B )
T
NIL
Listing 6.15: -
12
17
( defun zigzag ( n )
( flet (( move ( i j )
( if ( < j (1- n ) )
( values ( max 0 (1- i ) ) (1+
( values (1+ i ) j ) ) ) )
( loop with a = ( make-array ( list n n )
with x = 0
with y = 0
for v from 0 below (* n n )
do ( setf ( aref a x y ) v )
( if ( evenp (+ x y ) )
( setf ( values x y ) ( move
( setf ( values y x ) ( move
finally ( return a ) ) ) )
0 1 5
2 4 7
3 8 12
9 11 17
10 18 19
6
13
16
20
23
j))
: element-type integer )
x y))
y x)))
14
15
21
22
24
10
( defun s i e v e - o f - e r a t o s t h e n e s ( maximum )
( let (( composites ( make-array (1+ maximum ) : element-type bit
: in i ti al - el em e nt 0) ) )
( loop for candidate from 2 to maximum
when ( zerop ( bit composites candidate ) )
collect candidate
and do ( loop for composite from ( expt candidate 2) to maximum by
candidate
do ( setf ( bit composites composite ) 1) ) ) ) )
6. COMMON LISP
192
14
19
24
[1] P. Seibel, Practical Common Lisp. Apress, 2005.
[2] G. Kiczales, J. des Rivieres, D. G. Bobrow, The Art of the Metaobject Protocol. The MIT
Press, 1991.
[3] P. Graham, ANSI Common Lisp. Prentice Hall, 1995.
[4] P. Graham, On Lisp: Advanced Techniques for Common Lisp. Prentice Hall, 1993.
[5] G. Steele, Common Lisp: The Language. Digital Press, 2nd ed., 1990.
193
7.1
z = sin(x)sin(y) (. . 7.1) , , , , z. z, : .
0.5
1
0
0
1
2
0.5
0
0
. 7.1: z = sin(x)sin(y)
:
, (, ). ,
:
j = j
J(),
j
J() .
.
.
194
7.
195
Listing 7.1:
import operator
2
def s in si n _g ra d ie n t ( vec ) :
x , y = vec
return array ([ cos ( x ) * sin ( y ) ,
sin ( x ) * cos ( y ) ])
def gdescent ( initial , gradient_fn , step_fn = operator . sub ,
maxiter =1000 , eps =0.01 , precision =0.00001) :
12
x = initial
for i in range ( maxiter ) :
old_x = x . copy ()
x = step_fn ( old_x , eps * gradient_fn ( x ) )
17
[2; 1].
0.5
1
0
0
1
2
7.1.1
0.5
0
0
, ,
.
(2 )
(1000$)
120
90
...
4
3
...
157
120
...
7.
196
-
. .
h (x) = 0 + 1 x1 + 2 x2 ,
i ( ), x0 = 1.
h(x) =
n
X
i xi = T x.
i=0
- i . h(x) . :
m
J() =
1X
(h (x(i) ) y (i) )2 .
2 i=1
, .
j :
1
(h (x) y)2
J() =
j
j 2
1
= 2 (h (x) y)
(h (x) y)
2
j
!
n
X
= (h (x) y)
i xi y
j i=0
= (h (x) y)xj .
, :
(i)
j = j (h (x)(i) y (i) )xj .
,
. m,
j = j
m
X
(i)
(h (x)(i) y (i) )xj .
i=1
, , .
. 0 1 .
def lg_gradient ( p ) :
def fn ( x ) :
return p [0] + p [1] * x
4
7.
197
400
300
200
100
0
0
1,000
2,000
3,000
4,000
Square (f t )
. 7.2: .
7.2
() . .
7.2.1
(b) j,
Pm
(i)
= j}x(i)
i=1 1{c
j = P
.
m
(i) = j}
i=1 1{c
7.
198
:
1. .
2. .
3. .
4. , 2.
:
.
.
.
,
.
7.2.2
(, )
- . , k . , .
d(p, q) p q. p =
(p1 , . . . , pn ) q = (q1 , . . . , qn ), :
v
u n
uX
d(p, q) = t (pk qk )2 .
k=1
, ,
, .
, .
, , , , ,
.
from math import sqrt
3
7.
199
X Y . 1 +1, .
:
X,Y =
cov(X, Y )
E[(X X )(Y Y )]
=
,
X Y
X Y
cov , E , X Y .
, , :
Pn
1
(X
X)
(Y
Y
)
i
i=1
i=1 i
n1
n1
Pn
2
(X
X)
i
i=1
i=1 (Yi Y )
Y .
X
, :
n
1 X
r=
n 1 i=1
Xi X
sX
1
n
Pn
i=1
Xi
Yi Y
sY
1
n
Pn
i=1
Yi , .
.
, . ,
E[(X X )(Y Y )] = E(XY ) X Y ,
E[(X X )(Y Y )]
p
=
(E[(X X )2 ]) (E[(Y Y )2 ])
E(XY ) X Y
p
=p
.
2
(E[X ] 2X ) (E[Y 2 ] 2Y )
Pn
Pn
Pn
1
1
i=1 Xi Yi n2
i=1 Xi
i=1 Yi
n
q
r= q P
=
Pn
Pn
Pn
n
1
1
1
2
2 (1
2
2
X
X
)
Y
Y
)
(
i=1 i
i=1 i
i=1 i
i=1 i
n
n
n
n
Pn
Pn
Pn
X
Y
i
i
i=1
i=1
i=1 Xi Yi
n
r
.
=r
Pn
Pn
2
2
Pn
P
X
Y
(
(
)
)
i
i
n
i=1
i=1
2
2
i=1 Xi
i=1 Yi
n
n
X,Y = p
,
2 .. . 1 ,
:
, , . ,
.
7.
200
7.1:
[-0.09; 0.0]
[-0.3; -0.1]
[-0.5; -0.3]
[-1.0; -0.5]
[0.0;
[0.1;
[0.3;
[0.5;
0.09]
0.3]
0.5]
1.0]
1 , ,
. , [1, 2, 3],
[1, 3, 5], - .
0 , .
Listing 7.2:
17
r = num / den
return r
7.2.3
14
7.
201
24
29
7.2.4
, ,
, , .
1
. 7.3 , .
. 7.4 k .
7.3
. , .
7.3.1
if nearest is None :
nearest = next
7.
202
14
:
1
7.3.2
kd
kd (. k-dimensional tree) ,
k- .
kd ,
k. , , .
7.
203
. 7.4: .
,
.
: -
, . ,
x, , x ,
, (xconcrete , 0, . . . );
. ,
.
kd
, , , .
:
,
x, .
7.
204
,
.
(2; 3), (5; 4), (9; 6), (4; 7), (8; 1), (7; 2). ,
. 7.5. , . 7.6.
7; 2
5; 4
2; 3
9; 6
4; 7
8; 1
. 7.5: kd .
10
8
6
4
2
0
10
x
. 7.6: kd .
kd .
13
7.
205
axis = depth % k
median = n // 2
dataset . sort ( key = lambda row : row [ " features " ][ axis ])
18
:
n O(n log2 n).
O(log n).
O(log n).
1
O(log n) ; O(k n1 k ) .