# CS2/examples/objects/OhKay.py David MacQuigg 9-Sept-07 '''TestRunner works with any experimental object having a "Coin" interface. Just set the parameter Expt to the name of the class you want to test.''' import Coins # module with classes to create various coins (experiments) Expt = Coins.BiasedCoin # the default class if no other is selected #** class TestRunner: '''Methods to run a sequence of trials, accumulate the results, and generate various result display formats. Save all input and output data as attributes attached to 'self', a TestRunner instance.''' # . def __init__(self, Expt=Expt, bias=0.6, numTrials=500): '''Initialize a TestRunner instance.''' self.Expt = Expt # name of the class to test self.bias = bias self.numTrials = numTrials self.totalT = 0 # initial values before the experiment is run self.totalF = 0 self.resultList = [] # . . def runTrials(self): gizmo = self.Expt(bias=self.bias) # a coinlike object # . . for trial in range(self.numTrials): result = gizmo.toss() ## print '***1', trial, result # ***debug printout if result == True: self.totalT += 1; self.resultList.append('T') elif result == False: self.totalF += 1; self.resultList.append('-') else: self.resultList.append('*') # . . . def display1(self): # Raw data (ugly!) return self.resultList # . . def display2(self): # Summary format format = ("Results of running experiment (with bias=%s) %s times: " "True=%3s, False=%3s" ) return format % (self.bias, self.numTrials, self.totalT, self.totalF) # . . def display3(self): # Tabular display of raw data line_length = 0; multiline = '' for result in self.resultList: multiline += result + ' ' line_length += 2 if line_length >= 60: multiline += '\n' # a new line line_length = 0 return multiline # . . . . #** if __name__ == '__main__': '''Run experiments with different values for the bias on each experiment. From the directory containing CSC127, the Unix command is: > python CSC127/examples/OhKay.py ''' testValues = [0.1, 0.3, 0.5, 0.7, 0.9] # values for the 'bias' parameter def unitTests(Expt=Expt, testValues=testValues): for tv in testValues: tr = TestRunner(Expt=Expt, bias=tv) # new TestRunner instance tr.runTrials() print tr.display2() return tr # keep the last test runner for later analysis # . . . tr = unitTests() # run all tests #**~