ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Fri, 05 Feb 2016 18:31:59 +0100Extracting coefficients from symbolic expressionshttps://ask.sagemath.org/question/32465/extracting-coefficients-from-symbolic-expressions/ Assume a list of symbolic expressions (x0, x1,... are symbolic variables) like
[0, -15*x1^3/x0^7 + 10*x1*x2/x0^6 - x3/x0^5, 15*x1^2/x0^6 - 4*x2/x0^5, -6*x1/x0^5, x0^(-4)]
I want to extract the integer coefficients and get as result
[[0], [-15, 10, -1], [15, -4], [-6], [1]]
What is the most efficient/elegant method to accomplish this?Fri, 05 Feb 2016 17:10:48 +0100https://ask.sagemath.org/question/32465/extracting-coefficients-from-symbolic-expressions/Answer by tmonteil for <p>Assume a list of symbolic expressions (x0, x1,... are symbolic variables) like</p>
<pre><code>[0, -15*x1^3/x0^7 + 10*x1*x2/x0^6 - x3/x0^5, 15*x1^2/x0^6 - 4*x2/x0^5, -6*x1/x0^5, x0^(-4)]
</code></pre>
<p>I want to extract the integer coefficients and get as result</p>
<pre><code>[[0], [-15, 10, -1], [15, -4], [-6], [1]]
</code></pre>
<p>What is the most efficient/elegant method to accomplish this?</p>
https://ask.sagemath.org/question/32465/extracting-coefficients-from-symbolic-expressions/?answer=32468#post-id-32468A possibility is to transform each element as a fraction and look at the coefficients of the numerator. The main issue is about the leading `0` which is not an element of the symbolic ring, and whose list of coefficients is empty. So here is a way (the `fill` function transforms `[]` into `[0]`):
sage: L = [0, -15*x1^3/x0^7 + 10*x1*x2/x0^6 - x3/x0^5, 15*x1^2/x0^6 - 4*x2/x0^5, -6*x1/x0^5, x0^(-4)]
sage: fill = lambda x : [0] if not x else x
sage: [fill(SR(p).fraction(ZZ).numerator().coefficients()) for p in L]
[[0], [-15, 10, -1], [15, -4], [-6], [1]]
Fri, 05 Feb 2016 18:31:59 +0100https://ask.sagemath.org/question/32465/extracting-coefficients-from-symbolic-expressions/?answer=32468#post-id-32468