- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProblem.py
More file actions
Latest commit
335 lines (265 loc) · 10.5 KB
/
Copy pathProblem.py
File metadata and controls
335 lines (265 loc) · 10.5 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
importjson
fromUserDictimportIterableUserDict
## topcoder problem pieces ##
# main pieces
P_PROBLEM_NUMBER='number'
P_PROBLEM_NAME='name'
P_PROBLEM_STATEMENT='statement'
P_PROBLEM_DEFINITION='definition'
P_PROBLEM_CONSTRAINTS='constraints'
P_PROBLEM_EXAMPLES='examples'
P_PROBLEM_TESTS='tests'
# internal processing pieces
P_SUBMISSION_LISTING_LINK='submission_list_link'
P_SUBMISSION_LINK='submission_link'
# HTML-only pieces
P_PAGE_TITLE='page_title'
## topcoder problem structure ##
EMPTY_DEFINITIONS_DICT= {
'class': None,
'method': None,
'types': {
'output': None,
'input': []
},
'names': {
'input': []
}
}
EMPTY_EXAMPLE_DICT= {
'input': [],
'output': None,
'comment': None
}
EMPTY_PROBLEM_DICT= {
P_PROBLEM_NUMBER: None,
P_PROBLEM_NAME: None,
P_PROBLEM_STATEMENT: None,
P_PROBLEM_DEFINITION: dict(EMPTY_DEFINITIONS_DICT),
P_PROBLEM_CONSTRAINTS: [],
P_PROBLEM_EXAMPLES: [], # each example is {'input': [], 'output': None, 'comment': None}
P_PROBLEM_TESTS: [] # each test is {'input': [], 'output': None}
}
## html output parameters ##
MAIN_HEADER_LEVEL=1
HEADER_LEVEL=2
SUB_HEADER_LEVEL=3
## JSON output parameters ##
JSON_INDENT_LEVEL=4
## python output parameters ##
PYTHON_TEMPLATE="""#!/usr/bin/python
def %s:
pass
"""
## test icons ##
CHECK_MARK='Y'# u'\u2713'
CROSS_MARK='N'# u'\u2717'
STOP_MARK='X'# u'\u25A0'
classProblem(object, IterableUserDict):
"""The class for all TopCoder problems.
Inherits from IterableUserDict, and supports all regular dictionary
access."""
## init ##
def__init__(self, json_filename=None):
"""Creates a blank problem object.
If given a JSON filename, loads the data from that file."""
ifjson_filename!=None:
json_file=open(json_filename, 'rU')
self.data=json.load(json_file)
json_file.close()
else:
self.data=dict(EMPTY_PROBLEM_DICT)
## private object methods ##
def_generate_signature(self):
"""Returns the method signature for the problem, in the form
<return type> <name>(<type> <name>, <type> <name>, ...)
e.g. long MyFunc(int A, int B)
"""
signature="%s %s("% (self['definition']['types']['output'], self['definition']['method'])
foriinrange(len(self['definition']['types']['input'])):
signature+=str(self['definition']['types']['input'][i])
signature+=' '
signature+=str(self['definition']['names']['input'][i])
# add a comma, if its not the last one
ifi!=len(self['definition']['types']['input']) -1:
signature+=', '
signature+=")"
returnsignature
def_generate_mini_signature(self):
"""Returns the method signature for the problem, in the form
<name>(<name>, <name>, ...)
e.g. MyFunc(A, B)
"""
signature="%s("%self['definition']['method']
signature+=", ".join([str(x) forxinself['definition']['names']['input']])
signature+=")"
returnsignature
def_generate_filled_signature(self, inputs=None, output=None):
"""Returns the method signature for the problem with the given inputs
and output, in the form
<name>(<name>, <name>, ...) = <output>
e.g. MyFunc("A", 1) = 12
If no output is given, this does not add the equals sign.
Similarly, if no input is given, only adds the equals sign and the part
after it."""
signature=""
# add inputs
ifinputs!=None:
signature+="%s("%self['definition']['method']
signature+=", ".join([repr(x) forxininputs])
signature+=")"
# separate inputs and output (if adding both)
ifinputs!=Noneandoutput!=None:
signature+=" "
# add output
ifoutput!=None:
signature+="= %r"%output
returnsignature
def_piece_to_html(self, piece):
"""Converts the given piece to HTML, returning it as a string.
Does NOT return the HTML header for the piece, just the content."""
ifpiece==P_PROBLEM_NUMBER:
returnhtml_text(self[piece])
elifpiece==P_PROBLEM_NAME:
returnhtml_text(self[piece])
elifpiece==P_PROBLEM_STATEMENT:
returnhtml_text(self[piece])
elifpiece==P_PROBLEM_DEFINITION:
html=""
html+=html_header(SUB_HEADER_LEVEL, "Filename")
html+=html_text("%s.py"%self[piece]['class'])
html+=html_header(SUB_HEADER_LEVEL, "Signature")
html+=html_text(self._generate_signature())
returnhtml
elifpiece==P_PROBLEM_CONSTRAINTS:
return"<ul><li>"+"</li><li>".join(self[piece]) +"</li></ul>"
elifpiece==P_PROBLEM_EXAMPLES:
html=""
html+="<ul>"
forexampleinself[piece]:
html+="<li>"
html+=self._generate_filled_signature(example['input'], example['output'])
ifexample['comment']:
html+=example['comment']
html+="</li>"
html+="</ul>"
returnhtml
elifpiece==P_SUBMISSION_LISTING_LINK:
# not needed for HTML
returnNone
elifpiece==P_SUBMISSION_LINK:
# not needed for HTML
returnNone
elifpiece==P_PROBLEM_TESTS:
# not shown in HTML
returnNone
elifpiece==P_PAGE_TITLE:
return"%s. %s"% (self[P_PROBLEM_NUMBER], self[P_PROBLEM_NAME])
else:
# not recognised
returnNone
def_pieces_to_html(self, pieces):
"""Converts the given pieces to HTML, returning them as a list."""
return [_piece_to_html(x) forxinpieces]
def_run_test_list(self, tests, method):
"""Runs a given list of tests against the given method, returning True
if they all passed, False if not."""
fortestintests:
printself._generate_filled_signature(test['input']),
try:
result=method(*test['input'])
ifresult==None:
raiseException("Function did not return anything.")
printself._generate_filled_signature(output=result),
ifresult!=test['output']:
printCROSS_MARK
returnFalse
printCHECK_MARK
exceptException, e:
print"%s (%s)"% (STOP_MARK, str(e))
returnFalse
returnTrue
## public object methods ##
defrun_examples(self, method):
"""Runs all the examples on the given method, returning True if they
all passed, False if not.
"""
returnself._run_test_list(self[P_PROBLEM_EXAMPLES], method)
defrun_tests(self, method):
"""Runs all the tests on the given method, returning True if they
all passed, False if not.
"""
returnself._run_test_list(self[P_PROBLEM_TESTS], method)
deftest_method(self, method):
"""Runs all examples and tests on the given method, returning True if
they all passed, False if not."""
ifself[P_PROBLEM_EXAMPLES]:
print"-- Running examples --"
result=self.run_examples(method)
ifresult==False:
print"-- Failed --"
returnFalse
print"-- All passed! --"
ifself[P_PROBLEM_TESTS]:
print"-- Running tests --"
result=self.run_tests(method)
ifresult==False:
print"-- Failed --"
returnFalse
print"-- All passed! --"
returnTrue
# python output #
defto_python(self, template=PYTHON_TEMPLATE):
"""Returns a Python file, with the method header, according to the
specified python template."""
returnPYTHON_TEMPLATE%self._generate_mini_signature()
defto_python_file(self, filename, template=PYTHON_TEMPLATE):
"""Saves Python text to a file, with the method header, according to the
specified python template."""
python_file=open(filename, 'w')
python_file.write(self.to_python())
python_file.close()
# json output #
defto_json(self):
"""Returns the problem, as a JSON string."""
returnjson.dumps(self.data, indent=JSON_INDENT_LEVEL)
defto_json_file(self, filename):
"""Saves the problem in JSON format to the given filename."""
json_file=open(filename, 'w')
json.dump(self.data, json_file, indent=JSON_INDENT_LEVEL)
json_file.close()
# html output #
defto_html(self):
"""Returns the problem, as an HTML string."""
html=u""
# add title
html+="<html><head><title>%s</title></head><body>"%self._piece_to_html(P_PAGE_TITLE)
html+=html_header(1, self._piece_to_html(P_PAGE_TITLE))
# add each piece
html+=html_header(2, "Problem")
html+=self._piece_to_html(P_PROBLEM_STATEMENT)
html+=html_header(2, "Definition")
html+=self._piece_to_html(P_PROBLEM_DEFINITION)
ifself[P_PROBLEM_CONSTRAINTS]:
html+=html_header(2, "Constraints")
html+=self._piece_to_html(P_PROBLEM_CONSTRAINTS)
ifself[P_PROBLEM_EXAMPLES]:
html+=html_header(2, "Examples")
html+=self._piece_to_html(P_PROBLEM_EXAMPLES)
# escape non-ascii characters with HTML
returnhtml.encode('ascii', 'xmlcharrefreplace')
defto_html_file(self, filename):
"""Saves the problem in HTML format to the given filename.
Writes in the given html encoding."""
html_file=open(unicode(filename), 'w')
html_file.write(self.to_html())
html_file.close()
## helper functions ##
defhtml_header(level, text):
"""Returns an HTML header, containing the specified text.
The level indicates the size of the header (1 for the largest header, larger
numbers for deeper headers)."""
return"<h%d>%s</h%d>"% (level, text, level)
defhtml_text(text):
"""Returns some text in HTML format."""
return"<p>%s</p>"%text