On Mon, Nov 10, 2008 at 10:15 PM, Brian Granger <[EMAIL PROTECTED]> wrote:
>
> OK, sounds great.  Now a follow on....or two...
>
> * How can I get the non-commuting part of the Mul?  I see that
> Mul.flatten knows about it, but I don't see how to get it back.

You need to do something like:

[p for p in a.args if not p.is_commutative]

where "a" is the (Mul) expression containing commutative and
non-commutative parts. If you want to get it as a Mul, do:

Mul(*[p for p in a.args if not p.is_commutative])

>
> * I then need to take an expression, find all the instances of Mul in
> the tree and replace those by something else, one by one.  Is there a
> simple way of doing this?  the most common usage case that I will have
> is a sum of terms;
>
> 3*A*B*|state1> + 4*C*D*|state>

The best thing is to loop through the expression, so something like:

from sympy.interactive import *

e = x**2+(y*x+2)**3*z + z*x

def change_mul(a):
    return a**2

def walk(node):
    args_new = []
    for arg in node.args:
        if arg.is_Mul:
            args_new.append(change_mul(arg))
        else:
            args_new.append(walk(arg))
    if len(args_new) > 0:
        return node.__class__(*args_new)
    else:
        return node


print e
print walk(e)


This prints:

x*z + x**2 + z*(2 + x*y)**3
x**2 + x**2*z**2 + z**2*(2 + x*y)**6

i.e. each Mul is powered to 2.  I agree that we should maybe even
simplify this --- if you (or anyone!) has any ideas how to make this
even simpler, let's implement it. Maybe even something like:

def walk(node):
    args_new = []
    for arg in node.args:
        if arg.is_Mul:
            args_new.append(change_mul(arg))
        else:
            args_new.append(walk(arg))
    return node.__class__(*args_new)


This would require Symbols to have the actual name of the symbol in
.args(). But so far our policy was to only have Basic objects as args,
which imho is a good policy. Any thoughts are welcome.

Ondrej

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To post to this group, send email to sympy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/sympy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to