Python对拍器

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
# 对拍器
# 用gen.cpp生成数据,用std.cpp生成标准答案,用test.cpp生成测试答案,用check.py对拍
# 所有文件都在同一文件夹下

# 一直循环,直到对拍出错
# 正确输出:#序号 Accepted
# 错误输出:#序号 Wrong Answer!!

import os
import re
import time

# 不含后缀的文件名
filename_mycode = 'test' # 测试代码
filename_std = 'std' # 标准答案
filename_generate = 'gen' # 生成数据

# 确认文件存在,否则报错
def checkfile(filename):
print('Checking', filename)
if not os.path.exists(filename):
print('File not found:', filename)
exit(0)

checkfile(filename_mycode + '.cpp')
checkfile(filename_std + '.cpp')
checkfile(filename_generate + '.cpp')

# 编译
def compile(filename):
print('Compiling', filename)
os.system('g++ ' + filename + '.cpp -o ' + filename )

compile(filename_mycode)
compile(filename_std)
compile(filename_generate)

# 生成数据和答案
def generate():
os.system('.\\' + filename_generate + ' > in.txt')
os.system('.\\' + filename_std + ' < in.txt > std.txt')
os.system('.\\' + filename_mycode + ' < in.txt > out.txt')

# 比较2个文件是否相同,不同则返回行列号
def compare(file1, file2):
f1 = open(file1, 'r')
f2 = open(file2, 'r')
lines1 = f1.readlines()
lines2 = f2.readlines()
if(len(lines1) != len(lines2)):
return -1, '', ''
for i in range(len(lines1)):
obj1 = lines1[i].split()
obj2 = lines2[i].split()
if len(obj1) != len(obj2):
return i, lines1[i], lines2[i]
for j in range(len(obj1)):
if obj1[j] != obj2[j]:
return i, obj1[j], obj2[j]
return 0, '', ''

# 对拍
def check():
i = 1
while True:
generate()
line, line1, line2 = compare('std.txt', 'out.txt')
if line == 0:
print('#', i, 'Accepted')
elif line == -1: # 行数不同
print('#', i, 'Wrong Answer!!')
print('Line:', 'Different number of lines')
break
else: # 内容不同
print('#', i, 'Wrong Answer!!')
print('Line:', line)
print('Standard:', line1)
print('Output:', line2)
break
i += 1

check()