Proving optimized function is still correct

salvasan at yahoo.com salvasan at yahoo.com
Mon Nov 12 20:41:13 EST 2001


A gave a colleague of mine a Python function to optimise:

def count_combos( m, n, trial=[] ):
    #is trial complete?
    if len(trial) == m:
        #check if trial is valid
        total = 0
        for x in trial:
            total = total + x
        if total == n:
            #count this valid trial
            return 1
        #otherwise do not count it
        return 0
    else:
        #RECURSIVE CALL
        count = 0
        for i in range( n+1 ):
             #extend trial by another test element
             trial.append(i)
             #total up valid trials found
             count = count + count_combos( m, n, trial )
             #remove last appended element
             del( trial[-1] )
        return count

The preconditions are that arguments m and n are always positive integers.
She amazingly reduced the above code to the following:

def count_combos_optimised( m, n ):
    numer = 1
    denom = 1
    j = m+n-1
    i = 1
    while i<m:
        numer = numer * j
        denom = denom * i
        j = j - 1
        i = i + 1
    return numer/denom

I've tried a whole bunch of values for m and n and so far both
functions return identical results.

count_combos( 6, 4 ) and count_combos_optimised( 6, 4 ) both return 126

The optimised version operates a lot faster, but how can I be sure
that count_combos_optimised( m, n ) and count_combos( m, n ) will
return the same values for every possible pairing of positive integers
(m,n) ? There could very well be some pair of six digit numbers upon
which they disagree, or maybe no such pair exists, but is there a way
to tell either way?






More information about the Python-list mailing list