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.Tue, 15 Sep 2020 06:23:30 +0200Coefficient of Polynomial Function in a loophttps://ask.sagemath.org/question/53457/coefficient-of-polynomial-function-in-a-loop/ Hello so I am using the .coefficient function to extract the coefficient of a monomial given some polynomial. For example, 3x^(2).coefficient(x^(2)) is 3.
R.<x,y,z,w> = QQ[]
List1= [x^(2), y^(2),z^(2)]
List2= [x^(2)+y^(2)+z^(2), 3*x^(2),4*y^(2)]
List3=[]
For example if I do List2[0].coefficient(List1[0]), Sage immediately outputs 1. However, when I try to run it through all of List1, for some reason, the runtime seems to go forever so I feel I am doing something wrong. Even if I restrict to only the first term in List2, the runtime is very long and doesn't stop. Am I doing something wrong? In the code below, it should only run through 3 terms.
i=0
while i<len(List1):
Result=List2[0].coefficient(List1[i])
List3.append(Result)
i+=1Tue, 15 Sep 2020 01:40:53 +0200https://ask.sagemath.org/question/53457/coefficient-of-polynomial-function-in-a-loop/Answer by John Palmieri for <p>Hello so I am using the .coefficient function to extract the coefficient of a monomial given some polynomial. For example, 3x^(2).coefficient(x^(2)) is 3. </p>
<pre><code>R.<x,y,z,w> = QQ[]
List1= [x^(2), y^(2),z^(2)]
List2= [x^(2)+y^(2)+z^(2), 3*x^(2),4*y^(2)]
List3=[]
</code></pre>
<p>For example if I do List2[0].coefficient(List1[0]), Sage immediately outputs 1. However, when I try to run it through all of List1, for some reason, the runtime seems to go forever so I feel I am doing something wrong. Even if I restrict to only the first term in List2, the runtime is very long and doesn't stop. Am I doing something wrong? In the code below, it should only run through 3 terms.</p>
<pre><code>i=0
while i<len(List1):
Result=List2[0].coefficient(List1[i])
List3.append(Result)
i+=1
</code></pre>
https://ask.sagemath.org/question/53457/coefficient-of-polynomial-function-in-a-loop/?answer=53459#post-id-53459The indentation in your second code block is wrong, but if you fix that (don't indent `while`, indent all of the lines after it), it works, at least for me. The code can also be rewritten a few ways:
No need for the variable `i`:
for a in List1:
Result = List2[0].coefficient(a)
List3.append(Result)
In fact, no need for an explicit loop at all, using list comprehension instead:
List3 = [List2[0].coefficient(a) for a in List1]
By the way, there are other ways to get at the coefficients. For example:
a = x^2 + 2*y^2 + 3*z^2
for b in a:
print(b)
will print
(1, x^2)
(2, y^2)
(3, z^2)
You can get the same information using list comprehension, `[b for b in a]`, or in fact just `list(a)`.Tue, 15 Sep 2020 06:23:30 +0200https://ask.sagemath.org/question/53457/coefficient-of-polynomial-function-in-a-loop/?answer=53459#post-id-53459