wow this is a bit over my range of knowledge im impressed :) ill be happy to look at it but i think i will see if i can end up writing my own :) worse case ill do it by hand will not take long hmm wow thanks :)

On Sep 10, 2007, at 8:47 PM, John Fouhy wrote:

#######
import operator

binops = { 'add':operator.add,
           'sub':operator.sub,
           'mul':operator.mul,
           'div':operator.truediv,
           'pow':operator.pow,
           'join':lambda x, y: int(str(x)+str(y))
           }

patterns = { 'add':'(%s) + (%s)',
             'sub':'(%s) - (%s)',
             'mul':'(%s) * (%s)',
             'div':'(%s) / (%s)',
             'pow':'(%s)^(%s)',
             'join':'%s%s'
             }

def combine(digits):
    """ digits :: set(int)

    output :: [ (value, expression) ]
      value :: int
      expression :: str -- string representation of math expression
    """

    # We're going to solve this instance in terms of the solution
    # for a list with one fewer digit.

    # Because of non-commutativity, we have to do this twice for each
    # possible start digit.

    res = []

    # Base case.
    if len(digits) == 1:
        return [(digit, str(digit)) for digit in digits]

    # Otherwise..
    for digit in digits:
        remainder = digits - set([digit])

        for val, exp in combine(remainder):
            for binop in binops:
                if binop == 'join':
                    # Ensure we only join numbers, not expressions.
                    try:
                        int(exp)
                    except ValueError:
                        continue

                try:
                    newval1 = binops[binop](digit, val)
                    pattern1 = patterns[binop] % (str(digit), exp)
                    res.append((newval1, pattern1))
                except ZeroDivisionError:
                    pass

                try:
                    newval2 = binops[binop](val, digit)
                    pattern2 = patterns[binop] % (exp, str(digit))
                    res.append((newval2, pattern2))
                except ZeroDivisionError:
                    pass

    return res

if __name__ == '__main__':
    res = combine(set(range(1, 4)))

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to