-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
138 lines (117 loc) · 4.47 KB
/
utils.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
from cStringIO import StringIO
import sys
from random import random, randint, choice
import json
import subprocess
import tempfile
import os
RANDOM_WORD = ['hello', 'socks', 'benjamin', 'hurshal', 'lu' 'world', 'moo', 'cow', 'apple', 'banana', 'pumpkin', 'abibliophobia', 'bumbershoot', 'codswallop', 'borborygm', 'batrachomyomachy', 'truffle', 'cherry', 'orange', 'fruit', 'lolipop', 'biscuit', 'manatee', 'pingpong', 'traffic', 'pop', 'oyster', 'bread', 'pineapple', 'mango', 'kiwi', 'strawberry', 'blueberry', 'raspberry', 'caramel', 'chocolate', 'cookie', 'papaya']
RANDOM_SENTENCE = ['i want it that way', 'breaking bad is awesome', 'terra nova is the best tv show', 'cows moo but chickens bawk', 'bunnies are cute', 'you are my fire my one desire', 'harry potter harry potter ron weasley', 'lol its frodo baggins', "im going to make him an offer he cant refuse", 'may the force be with you', "ill be back", 'mama always said life was like a box of chocolates', 'The best time to plant a tree was 20 years ago The second best time is now', 'mark twain once said something about lightning bugs and lightning']
# These functions may be used in template generation code in problem files
rand_choice = choice
rand_int = randint
def rand_letter():
ascii_val = 0
if random() < 0.5:
ascii_val = randint(65, 90)
else:
ascii_val = randint(97, 122)
return chr(ascii_val)
def rand_char():
return chr(randint(32, 126))
def rand_word():
return choice(RANDOM_WORD)
def rand_sentence():
return choice(RANDOM_SENTENCE)
def rand_string():
res = rand_sentence()
for i in range(rand_int(0, 5)):
idx = rand_int(0, len(res)-1)
res = res[:idx] + rand_char() + res[idx:]
return res
def rand_word_list(n):
res = []
for i in range(n):
res.append(rand_word())
return res
def rand_word_list_list(n):
res = []
for i in range(n):
res.append(rand_word_list(randint(1, 10)))
return res
def rand_sentence_list(n):
res = []
for i in range(n):
res.append(rand_sentence())
return res
def rand_string_list(n):
res = []
for i in range(n):
res.append(rand_string())
return res
def rand_int_list(n):
res = []
for i in range(n):
res.append(randint(-100, 100))
return res
def rand_int_list_list(n):
res = []
for i in range(n):
res.append(rand_int_list(randint(1, 10)))
return res
def rand_sidict():
res = {}
for i in range(20):
res[choice(RANDOM_WORD)] = randint(-100, 100)
return res
def nth(n):
nth = str(n)
if nth[-1] == '1' and (len(nth) < 2 or nth[-2] != '1'):
nth += 'st'
elif nth[-1] == '2' and (len(nth) < 2 or nth[-2] != '1'):
nth += 'nd'
elif nth[-1] == '3' and (len(nth) < 2 or nth[-2] != '1'):
nth += 'rd'
else:
nth += 'th'
return nth
# Replaces all template vars within a template,
# given template string and template_vars dict
def replace_template_vars(template, template_vars):
for template_string, value in template_vars.items():
template = template.replace('{{ ' + template_string + ' }}', value if isinstance(value, str) or isinstance(value, unicode) else json.dumps(value))
return template
# Generates expected output, given solution string and test string
def get_expected(solution, language_id, test=''):
#TODO detect language automatically
if language_id == 1:
old_stdout = sys.stdout
sys.stdout = StringIO()
exec(solution + '\n' + test, {})
expected = sys.stdout.getvalue()
sys.stdout = old_stdout
return expected
elif language_id == 2:
tmp = tempfile.NamedTemporaryFile(delete=False)
tmp.write(solution + '\n' + test)
tmp.close()
process = subprocess.Popen(['node', tmp.name], stdout=subprocess.PIPE)
out, err = process.communicate()
os.unlink(tmp.name)
return out
# Generates the template vars, given gen_template_vars string from problem file
# Returns a json object
def get_template_vars(gen_template_vars):
exec_env = globals().copy()
exec gen_template_vars in exec_env
return json.dumps(exec_env['res'])
# Generates a problem by filling its templates with template vars and its
# expected fields with expected outputs
def get_problem(problem, language_id):
specific_index = None
template_vars = json.loads(problem['template_vars'])
for name in ['prompt', 'solution', 'test', 'hint']:
problem[name] = replace_template_vars(problem[name], template_vars)
problem['expected_test'] = get_expected(problem['solution'], language_id, problem['test'])
problem['expected_no_test'] = get_expected(problem['solution'], language_id)
return problem