How to optimise this code?

J. Cliff Dyer jcd at sdf.lonestar.org
Tue Aug 21 12:20:35 EDT 2007


David N Montgomery wrote:
> class testCase:
>     def __init__(self, tc):
>         if tc == 1:self.testCase1()
>         if tc == 2:self.testCase2()
>         if tc == 3:self.testCase3()
>         if tc == 4:self.testCase4()
>         if tc == 5:self.testCase5()
>         if tc == 6:self.testCase6()
>
>     def testCase1(self):
>         print "tc1"
>
>     def testCase2(self):
>         print "tc2"
>
>     def testCase3(self):
>         print "tc3"
>
>     def testCase4(self):
>         print "tc4"
>
>     def testCase5(self):
>         print "tc5"
>
>     def testCase6(self):
>         print "tc6"
>
>
>     def testCaseX(self):
>         print "tcX"
>
> totalNumberOfTestCases = 6
> x = 0
> while x <= totalNumberOfTestCases:
>     x += 1
>     testCase(x)
>
>
> This template code is working, but I envisage having 100+ test cases and
> am concerned about my useage of if statements. I would be grateful for
> any pointers as to how I can run all tests cases, regardless of how
> many, in a more efficient manner.
>
> Thank you in advance.
>   

try binding each function to an element of a list, and then processing 
across the list.  This might look like:

def testCase1:
    return "tc1"
def testCase2:
    return "tc2"

testCaseList = []
testCaseList.append(testCase1)
testCaseList.append(testCase2)

for testCase in testCaseList:
    testCase()

Also, as python allows direct iteration over a list, you'll find that 
you don't need to create loops on an incrementor variable.  Just loop on 
the list itself. 

I suspect lambda might be your friend here too for making the code less 
verbose, though I never really got the hang of lambdas, even though my 
first programming experience was a scheme class way back when....  Ah well.

Hope this helps.

Cheers,
Cliff





More information about the Python-list mailing list