Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

This should be a built-in function, indeed. Here's a solution:

def convert(expr):
     op = expr.operator()
     ops = expr.operands()
     if op:
        if len(ops) == 2:
            return op(*map(convert, expr.operands()))
        else:
            return op(convert(expr.operands()[0]), reduce(op, map(convert, expr.operands()[1:])))
     else:
        return expr.convert() if hasattr(expr, 'convert') else expr

Then:

sage: blah = units.energy.joule/units.temperature.kelvin
sage: convert(blah)
kilogram*meter^2/(kelvin*second^2)

This should be a built-in function, indeed. Here's a solution:solution in the meanwhile:

def convert(expr):
     op = expr.operator()
     ops = expr.operands()
     if op:
        if len(ops) == 2:
            return op(*map(convert, expr.operands()))
        else:
            return op(convert(expr.operands()[0]), reduce(op, map(convert, expr.operands()[1:])))
     else:
        return expr.convert() if hasattr(expr, 'convert') else expr

Then:

sage: blah = units.energy.joule/units.temperature.kelvin
sage: convert(blah)
kilogram*meter^2/(kelvin*second^2)

This should be a built-in function, indeed. Here's a solution in the meanwhile:

def convert(expr):
     op = expr.operator()
     ops = expr.operands()
     if op:
        if len(ops) == 2:
            return op(*map(convert, expr.operands()))
ops))
        else:
            return op(convert(expr.operands()[0]), op(convert(ops[0]), reduce(op, map(convert, expr.operands()[1:])))
ops[1:])))
     else:
        return expr.convert() if hasattr(expr, 'convert') else expr

Then:

sage: blah = units.energy.joule/units.temperature.kelvin
sage: convert(blah)
kilogram*meter^2/(kelvin*second^2)