Operation tree

694 days ago by jason3

import operator as op 
       
mma_translate={op.add: "Plus", op.mul: "Times", op.pow: "Power", } 
       
def mma(x): try: s=x._mathematica_init_() return x._mathematica_init_() except: pass try: return mma_translate[x] except: return repr(x).capitalize() 
       
 
       
def tree(expr): if expr.operator() is None: return expr else: return [expr.operator()]+map(tree, expr.operands()) 
       
tree(x^2-x-2) 
       
[<built-in function add>, [<built-in function pow>, x, 2],
[<built-in function mul>, x, -1], -2]
[<built-in function add>, [<built-in function pow>, x, 2], [<built-in function mul>, x, -1], -2]
def expr_to_mma(expr): if expr.operator() is None: return "%s"%expr else: return mma(expr.operator())+"["+", ".join(map(expr_to_mma, expr.operands()))+"]" 
       
expr_to_mma(x^2-x) 
       
'Plus[Power[x, 2], Times[x, -1]]'
'Plus[Power[x, 2], Times[x, -1]]'
b=1/(sqrt(5)*sin(x-2)^2) 
       
expr_to_mma(b) 
       
'Times[Power[5, 1/2], Power[Sin[Plus[x, -2]], -2], 1/5]'
'Times[Power[5, 1/2], Power[Sin[Plus[x, -2]], -2], 1/5]'
b._mathematica_init_() 
       
'((5/1)^(1/2))*((Sin[(x)+(-2)])^(-2))*(1/5)'
'((5/1)^(1/2))*((Sin[(x)+(-2)])^(-2))*(1/5)'