/
stdio.py
278 lines (232 loc) · 7.31 KB
/
stdio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""
stdio.py
The stdio module supports reading from sys.stdin and writing to
sys.stdout.
Note: Usually it's a bad idea to mix these two sets of reading
functions:
-- isEmpty(), readInt(), readFloat(), readBool(), readString()
-- hasNextLine(), readLine(), readAll()
Usually it's better to use one set or the other exclusively.
"""
import sys
import re
#=======================================================================
# Writing functions
#=======================================================================
def writeln(x=''):
"""
Write x and an end-of-line mark to sys.stdout.
"""
sys.stdout.write(str(x) + '\n')
sys.stdout.flush()
#-----------------------------------------------------------------------
def write(x=''):
"""
Write x to sys.stdout.
"""
sys.stdout.write(str(x))
sys.stdout.flush()
#-----------------------------------------------------------------------
def writef(fmt, *args):
"""
Write each element of 'args' to sys.stdout. Use the format
specified by string 'fmt'.
"""
sys.stdout.write(fmt % args)
sys.stdout.flush()
#=======================================================================
# Reading functions
#=======================================================================
_buffer = ''
#-----------------------------------------------------------------------
def _readRegExp(regExp):
"""
Discard leading white space characters from sys.stdin. Then read
from sys.stdin and return a string matching regular expression
'regExp'. Raise an EOFError if no non-whitespace characters remain
in sys.stdin. Raise a ValueError if the next characters to be read
from sys.stdin do not match 'regExp'.
"""
global _buffer
if isEmpty():
raise EOFError()
compiledRegExp = re.compile(r'^\s*' + regExp)
match = compiledRegExp.search(_buffer)
if match == None:
raise ValueError()
s = match.group()
_buffer = _buffer[match.end():]
return s.lstrip()
#-----------------------------------------------------------------------
def isEmpty():
"""
Return True iff no non-whitespace characters remain in sys.stdin.
"""
global _buffer
while _buffer.strip() == '':
line = sys.stdin.readline()
if line == '':
return True
_buffer += line
return False
#-----------------------------------------------------------------------
def readInt():
"""
Discard leading white space characters from sys.stdin. Then read
from sys.stdin a sequence of characters comprising an integer.
Convert the sequence of characters to an integer, and return the
integer. Raise an EOFError if no non-whitespace characters remain
in sys.stdin. Raise a ValueError if the next characters to be read
from sys.stdin cannot comprise an integer.
"""
s = _readRegExp(r'[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)')
radix = 10
strLength = len(s)
if (strLength >= 1) and (s[0:1] == '0'): radix = 8
if (strLength >= 2) and (s[0:2] == '-0'): radix = 8
if (strLength >= 2) and (s[0:2] == '0x'): radix = 16
if (strLength >= 2) and (s[0:2] == '0X'): radix = 16
if (strLength >= 3) and (s[0:3] == '-0x'): radix = 16
if (strLength >= 3) and (s[0:3] == '-0X'): radix = 16
return int(s, radix)
#-----------------------------------------------------------------------
def readFloat():
"""
Discard leading white space characters from sys.stdin. Then read
from sys.stdin a sequence of characters comprising a float.
Convert the sequence of characters to a float, and return the
float. Raise an EOFError if no non-whitespace characters remain
in sys.stdin. Raise a ValueError if the next characters to be read
from sys.stdin cannot comprise a float.
"""
s = _readRegExp(r'[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?')
return float(s)
#-----------------------------------------------------------------------
def readBool():
"""
Discard leading white space characters from sys.stdin. Then read
from sys.stdin a sequence of characters comprising a bool.
Convert the sequence of characters to a bool, and return the
bool. Raise an EOFError if no non-whitespace characters remain
in sys.stdin. Raise a ValueError if the next characters to be read
from sys.stdin cannot comprise a bool.
These character sequences can comprise a bool:
-- True
-- False
-- 1 (means true)
-- 0 (means false)
"""
s = _readRegExp(r'(True)|(False)|1|0')
if (s == 'True') or (s == '1'):
return True
return False
#-----------------------------------------------------------------------
def readString():
"""
Discard leading white space characters from sys.stdin. Then read
from sys.stdin a sequence of characters comprising a string, and
return the string. Raise an EOFError if no non-whitespace
characters remain in sys.stdin.
"""
s = _readRegExp(r'\S+')
return s
def hasNextLine():
"""
Return True iff sys.stdin has a next line.
"""
global _buffer
if _buffer != '':
return True
else:
_buffer = sys.stdin.readline()
if _buffer == '':
return False
return True
#-----------------------------------------------------------------------
def readLine():
"""
Read and return as a string the next line of sys.stdin.
Raise an EOFError is there is no next line.
"""
global _buffer
if not hasNextLine():
raise EOFError()
s = _buffer
_buffer = ''
return s.rstrip('\n')
#-----------------------------------------------------------------------
def readAll():
"""
Read and return as a string all remaining lines of sys.stdin.
"""
global _buffer
s = _buffer
_buffer = ''
for line in sys.stdin:
s += line
return s
#=======================================================================
# For Testing
#=======================================================================
def _testWrite():
writeln()
writeln('string')
writeln(123456)
writeln(123.456)
writeln(True)
write()
write('string')
write(123456)
write(123.456)
write(True)
writeln()
writef('<%s> <%8d> <%14.8f>\n', 'string', 123456, 123.456)
writef('formatstring\n')
def _testReadInt():
while not isEmpty():
i = readInt()
writeln('Int: ' + str(i))
def _testReadFloat():
while not isEmpty():
f = readFloat()
writeln('Float: ' + str(f))
def _testReadBool():
while not isEmpty():
b = readBool()
writeln('Bool: ' + str(b))
def _testReadString():
while not isEmpty():
s = readString()
writeln('String: ' + s)
def _testReadLine():
while hasNextLine():
line = readLine()
write('Line: ' + line)
def _testReadAll():
s = readAll()
write(s)
def main():
"""
For testing.
"""
_testWrite()
write('Integer: ')
i = readInt()
writeln('Integer: ' + str(i))
write('Float: ')
f = readFloat()
writeln('Float: ' + str(f))
write('Bool: ')
b = readBool()
writeln('Bool: ' + str(b))
write('String: ')
s = readString()
writeln('String: ' + s)
#_testReadInt()
#_testReadFloat()
#_testReadBool()
#_testReadString()
#_testReadLine()
#_testReadAll()
if __name__ == '__main__':
main()