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.Sun, 12 Jul 2020 02:30:17 +0200Make program act on itself by entering certain areas of code (as a string) which it must itself executehttps://ask.sagemath.org/question/52412/make-program-act-on-itself-by-entering-certain-areas-of-code-as-a-string-which-it-must-itself-execute/My program must act on itself by entering certain areas of code (in the form of a string) which it must itself execute.
Take the ring `K` of polynomials with four unknowns `x_00`, `x_10`, `x_01` and `x_11`.
K.<x_00, x_10, x_01, x_11> = QQ []
g = K.random_element()
for i in range(1):
for j in range(1):
2 + g.monomial_coefficient(x_ij)
The last command tries to add to 2 the coefficient of the monomial `x_ij`. This is where it blocks.Sat, 11 Jul 2020 03:52:51 +0200https://ask.sagemath.org/question/52412/make-program-act-on-itself-by-entering-certain-areas-of-code-as-a-string-which-it-must-itself-execute/Answer by slelievre for <p>My program must act on itself by entering certain areas of code (in the form of a string) which it must itself execute. </p>
<p>Take the ring <code>K</code> of polynomials with four unknowns <code>x_00</code>, <code>x_10</code>, <code>x_01</code> and <code>x_11</code>.</p>
<pre><code>K.<x_00, x_10, x_01, x_11> = QQ []
g = K.random_element()
for i in range(1):
for j in range(1):
2 + g.monomial_coefficient(x_ij)
</code></pre>
<p>The last command tries to add to 2 the coefficient of the monomial <code>x_ij</code>. This is where it blocks.</p>
https://ask.sagemath.org/question/52412/make-program-act-on-itself-by-entering-certain-areas-of-code-as-a-string-which-it-must-itself-execute/?answer=52432#post-id-52432## Apply a map to all coefficients of a polynomial
To apply a map to all coefficients of a polynomial, use `map_coefficients`.
For example, say we want to add two to each coefficient.
The function $x \mapsto x + 2$ is denoted in Python by `lambda x: x + 2`.
sage: K.<x_00, x_10, x_01, x_11> = QQ []
sage: g = K.random_element()
sage: g
7/18*x_00*x_01 + 51*x_00*x_11 - 126*x_01*x_11 - x_10
sage: g.map_coefficients(lambda x: x + 2)
43/18*x_00*x_01 + 53*x_00*x_11 - 124*x_01*x_11 + x_10
In this case, 7/18 became 43/18, 51 became 53, -126 became -124, and -1 became +1.
Note that this works around the question.
## Accessing monomial $x_{ij}$ for given $i$ and $j$
For this, use string formatting. For instance:
sage: i = 0
sage: j = 1
sage: K(f'x_{i}{j}')
x_01Sun, 12 Jul 2020 02:30:17 +0200https://ask.sagemath.org/question/52412/make-program-act-on-itself-by-entering-certain-areas-of-code-as-a-string-which-it-must-itself-execute/?answer=52432#post-id-52432