Hi,

On Thu, Dec 30, 2010 at 01:34:07PM -0800, Jeff Cen wrote:
> 
> Hi,
> 
> Suppose I have already had an expression tree in a tree structure
> (like a nested list, say ['add', 'x', ['subtract', 'x', 'y']]), I
> would like to convert it to sympy expression and simplify it in sympy.
> 
> 
> When I read my tree structure, I first create an Add function. Then
> how can I append x and the rest?
> 

A simple helper function will do the job, e.g.:

In [1]: from sympy import *

In [2]: import operator

In [3]: mapping = {'add': operator.add, 'subtract': operator.sub}

In [4]: tree = ('add', 'x', ('subtract', 'x', 'y'))

In [5]: def convert(tree):
  ....:     op, a, b = tree
  ....:     if isinstance(a, tuple): a = convert(a)
  ....:     else: a = sympify(a)
  ....:     if isinstance(b, tuple): b = convert(b)
  ....:     else: b = sympify(b)
  ....:     return mapping[op](a, b)
  ....: 

In [6]: convert(tree)
Out[6]: -y + 2⋅x

> thanks
> 
> Jeff
> 
> 
>       
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sympy" group.
> To post to this group, send email to sy...@googlegroups.com.
> To unsubscribe from this group, send email to 
> sympy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sympy?hl=en.
> 

-- 
Mateusz

Attachment: signature.asc
Description: This is a digitally signed message part

Reply via email to