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.Wed, 27 Oct 2021 19:26:37 +0200Use expression.find with SR.wild in python scriptshttps://ask.sagemath.org/question/59497/use-expressionfind-with-srwild-in-python-scripts/I want to detect polynomials of the form `x^n + m` in a python script.
Found this helpful piece of code that works perfectly in sage's jupyter notebook:
x = var('x')
w0 = SR.wild(0)
w1 = SR.wild(1)
(x**2-2).find(x**w0+w1)
However, when I throw this into a `.py` file and run it I get the error `*** TypeError: unsupported operand parent(s) for ^: 'Symbolic Ring' and 'Symbolic Ring'`
**Minimal Failing Example:**
from sage.all import *
import sage
from sage.calculus.var import var
from sage.symbolic.ring import SymbolicRing
SR = SymbolicRing()
polynomial = SR('x^2-2')
x = var('x')
w0 = SR.wild(0)
w1 = SR.wild(1)
polynomial.find(x**w0+w1)
What am I missing?Wed, 27 Oct 2021 16:21:11 +0200https://ask.sagemath.org/question/59497/use-expressionfind-with-srwild-in-python-scripts/Answer by rburing for <p>I want to detect polynomials of the form <code>x^n + m</code> in a python script.</p>
<p>Found this helpful piece of code that works perfectly in sage's jupyter notebook:</p>
<pre><code>x = var('x')
w0 = SR.wild(0)
w1 = SR.wild(1)
(x**2-2).find(x**w0+w1)
</code></pre>
<p>However, when I throw this into a <code>.py</code> file and run it I get the error <code>*** TypeError: unsupported operand parent(s) for ^: 'Symbolic Ring' and 'Symbolic Ring'</code></p>
<p><strong>Minimal Failing Example:</strong></p>
<pre><code>from sage.all import *
import sage
from sage.calculus.var import var
from sage.symbolic.ring import SymbolicRing
SR = SymbolicRing()
polynomial = SR('x^2-2')
x = var('x')
w0 = SR.wild(0)
w1 = SR.wild(1)
polynomial.find(x**w0+w1)
</code></pre>
<p>What am I missing?</p>
https://ask.sagemath.org/question/59497/use-expressionfind-with-srwild-in-python-scripts/?answer=59501#post-id-59501The problem is that the `x` in `polynomial` is not the `x = var('x')`:
>>> x is polynomial.variables()[0]
False
It is better to be explicit:
>>> x = SR.var('x')
>>> polynomial = x**2 - 2
>>> polynomial.find(x**w0+w1)
[x^2 - 2]
>>> polynomial.match(x**w0+w1)
{$1: -2, $0: 2}
Or, if you would like to use the preparser:
>>> x = SR.var('x')
>>> polynomial = sage_eval('x^2 - 2', locals={'x' : x})Wed, 27 Oct 2021 19:26:37 +0200https://ask.sagemath.org/question/59497/use-expressionfind-with-srwild-in-python-scripts/?answer=59501#post-id-59501