On Thu, Jun 21, 2012 at 3:17 PM, Chris Smith <
smi...@gmail.com> wrote:
> On Thu, Jun 21, 2012 at 3:34 PM, Aaron Meurer <
asme...@gmail.com> wrote:
>> I don't think there's an efficient function to do it, if that's what you're
>> looking for (i.e., one that doesn't require full expansion). It's not too
>> hard to come up with, though.
>
> (I gave up when I started chasing the recursion rabbit...I don't think
> it's a trivial problem to handle it in a general way.)
You don't have to do it recursively. You just want the terms such that
k + m = N. Poly.monoms() gives all the monomials, ordered
lexicographically (i.e., by total degree).
For example, if the monomials for your polys are [5, 4, 3, 2, 1, 0]
and [4, 2, 1] (say you have x**5 + 2*x**4 - x**3 + x**2 - 2*x + 1 and
x**4 - x**2 + x), and you want the term in the product of degree 5,
then you just need to pair up (5, 0), (4, 1), (3, 2), (2, 3), (1, 4),
and (0, 5). In this case, only (4, 1), (3, 2), and (1, 4) are
non-zero, so the result is -2*1 + -1*-1 + 1*1 = 1. This can easily be
generalized to multivariate polynomials and total degree. You just
sum each term from monoms(), and be sure to catch all terms of
whatever degree you are looking for.
Aaron Meurer
>
>>
>
> Putting together some of the suggestions so far gives something like this:
>
>>>> def order(p, n):
> ... p = Poly(p, p.free_symbols or Dummy())
> ... gens = p.gens
> ... ok = []
> ... for m, c in p.terms():
> ... if sum(m) == n:
> ... ok.append(Mul(*[g**e for g, e in zip(gens, m)]))
> ... return ok
> ...
>>>> order(p, 2)
> [x*y, y**2]
>>>> p
> (x*y + 1)*(x + y**2 + 1)
>
> Note that making a Poly out of something automatically expands it. And
> using a Dummy in case there is no generator is necessary in case p is
> a constant.
>
> Regarding the question about getting the terms...If you don't use Poly
> and want the terms of an expression, Add.make_args(expr) will give you
> the terms that add together to give expr (even if expr isn't an Add).
> If you know expr is an Add then you could simply do expr.args to get
> the terms.
>
> /chris
>
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.