# -*- coding: utf-8 -*- #### DO NOT MODIFY THIS FILE #### #### #### This program checks the correctness of the program written by the students. Do not modify this program. #### Write your program in the file user.py and only there. #### import re import sys import os import subprocess # The (default) name of the file containing the user program. userfilename="user.py" # If the user specifies a filename when running this program then this is taken to be the # name of the user file. if len(sys.argv)>1: userfilename=sys.argv[1] # Prefix of the program files created automatically in order to check the user program (one file per test case). testerfilename="__testcode__" # The function below writes the python program that checks the user program on input inp and output outp. # firstline is the line number of the first line of the user's code and lastline is the line number of the last line. # fname is the name of the user file def maketestprog(inp, outp, firstline, lastline, fname): f = open(fname, 'w+') print >> f, "# -*- coding: utf-8 -*-" print >> f, "#### Checking file: {uf}".format(uf=userfilename) print >> f, "import sys, math" print >> f, "LLL={LLL}".format(LLL=inp) #### Change this (especially for string args) print >> f, "_L=LLL" #### Change this print >> f, "# start user code" for i in range(firstline, lastline+1): print >> f, lines[i], print >> f, "# end user code" mycommand = "uuu = histogram(_L)" #### Change this print >>f, """ import signal def _signal_handler(signum, frame): raise Exception("Timed out!") if hasattr(signal, 'SIGALRM'): signal.signal(signal.SIGALRM, _signal_handler) signal.alarm(3) # Timeout after 3 seconds. To catch infinite loops. try: {mycmd} except Exception, msg: print "Timed out!" else: {mycmd} if uuu != {uuu}: #### Change this print \"ERROR on input {LLL}\\nOutput produced is \", uuu, \"\\nShould be {uuu}\" sys.exit(1) else: print "OK" sys.exit(0) """.format(LLL=inp, uuu=outp, mycmd=mycommand) return fname # We list below in the lists inputs and outputs some input cases and the corresponding outputs. ddd = [-1]*50 inputs = [ [-1, 1, 0, 1, 2, -1], [], [1, 1, 2, 2, 2], ddd, ] outputs = [ {0: 1, 1: 2, 2: 1, -1: 2}, {}, {1:2, 2:3}, {-1: 50}, ] # lines = open(userfilename).readlines() for i,l in enumerate(lines): if re.match('####START', l): #print "START found at line %d, [%s]"% (i, l) firstline = i+1 if re.match('####STOP', l): #print "STOP found at line %d, [%s]"% (i, l) lastline = i-1 errors=0 for i,inp in enumerate(inputs): print print "-------------------Case No %d------------------"% i filename = maketestprog(inputs[i], outputs[i], firstline, lastline, testerfilename+str(i)+".py") exit_code = subprocess.call(["python", filename]) if exit_code == 0: print "---Case No %d: OK"% i else: errors += 1 print "---Case No %d: ERROR"% i print if errors>0: print "****** The program has run in error in some cases." sys.exit(1) else: print "****** The program has run correctly in all cases." sys.exit(0)