> My solution is as follows -
>
> def reduce_sqr(expr):
> args = expr.args
> if len(args) == 0:
> return(sqrt(expr))
> else:
> if str(type(expr)) == "<class 'sympy.core.power.Pow'>":
> args = expr.args
> if args[1] == 2:
> e_mag = args[0]
> else:
> e_mag = sqrt(expr)
> else:
> e_mag = 1
> for arg in args:
> if str(type(arg)) == "<class
> 'sympy.core.power.Pow'>":
> x = arg.args
> if len(x) == 2 and x[1] == 2:
> e_mag *= x[0]
> else:
> return(sqrt(expr))
> return(e_mag)
>
There are a few extra properties/function that you can use to make life easier.
Mul.make_args will treat an expression like a Mul so you can then
process args in a single loop
If you are dealing with a Pow (.is_Pow) then you can access the base
with .base, the exp with .exp and get both with .as_base_exp()
>>> def red_sqrt(s):
... out = []
... inn = []
... for m in Mul.make_args(s.base):
... if m.is_Pow:
... b, e = m.as_base_exp()
if e == 2:
... out.append(b)
... else:
... inn.append(m)
... return Mul(*out)*sqrt(Mul(*inn))
epath can be used to select all Pow at the top level of an expression, too:
>>> eq
x + (x**(1/2)*y**4*cos(x)*cos(x*y)**2)**(1/2)
>>> epath('/Pow', eq)
[(x**(1/2)*y**4*cos(x)*cos(x*y)**2)**(1/2)]
>>>
Notice that epath didn't pull out powers from inside the main sqrt and
it didn't return the x from eq
/c
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
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.