Ask Your Question

Revision history [back]

Here is a possible way:

Landscape (a concrete example to fix ideas):

sage: R.<x,y> = QQ[]
sage: P = x^2+x*y+x+2

Instead of a list (with possibly lot of zeroes), let me use a defaultdict to collect the polynomials:

sage: from collections import defaultdict
sage: d = defaultdict(P.parent())

Then we can feed it by iterating over the polynomial:

sage: for coeff,monom in P:
....:     d[monom.degree()] += coeff * monom

So we have:

sage: d
defaultdict(Multivariate Polynomial Ring in x, y over Rational Field, {0: 2, 1: x, 2: x^2 + x*y})
sage: d[0]
2
sage: d[1]
x
sage: d[2]
x^2 + x*y
sage: d[3]
0
sage: d[123]
0
sage: d[123].parent()
Multivariate Polynomial Ring in x, y over Rational Field
sage: sum(d[i] for i in d)
x^2 + x*y + x + 2
sage: sum(d[i] for i in d) == P
True