I am attempting to pass 2 functions to a python script via JSON in order to evaluate their equivalence. The issue I am having is that the input is in AsciiMath notation. It seems sympify has no issue parsing the expressions from the strings if the format is consistent with that of Python expressions. Is there a way to parse AsciiMath notation into something Python can interpret? I have been unable to find any libraries that offer such a feature.
PHP:
$data = array("2*x", "x*2"); // returns true as expected
$data = array("2x", "x2"); // AsciiMath notation does not work
$result = shell_exec('python /path/check.py ' . escapeshellarg(json_encode($data)));
Python:
import sys, json
from sympy import *
# Load the json data sent from PHP
try:
data = json.loads(sys.argv[1])
except:
sys.exit(1)
x = Symbol('x')
# Convert string inputs to expressions
user_response = sympify(data[0])
correct_answer = sympify(data[1])
# Perform equivalence comparison
result = user_response == correct_answer
# Return result
print json.dumps(result)
When asking a question like this, you should demonstrate the problem. Here's what I think is happening.
With one set of expressions,
sympifyworks fine:But with the other pair:
That's just for the '2x' string. For the other string:
sympifyis expecting strings that could evaluated in asympyenvironmentIt says
arbitrary, but the docs are somewhat more restrictive, as described.In the context of the question that means expressions using
xwhich was defined withbut ones using
ywould have problems.===
sympifyproduces asympyexpression:which can then be 'evaluated' in various ways. I could describe this a 'modified', except
sympystresses that the expression is immutable. These actions all produce new expressions or values:===
Also such an expression cannot be evaluated by the core Python interpreter,
Define a new symbol, and expression:
Reassigning
yto be a Python integer, does not change the value ofexpr:but it does allow us to evaluate a regular Python expression:
But the same Python expression using
xsymbol produces asympyexpression:===
https://docs.sympy.org/latest/modules/parsing.html
This
parsingmodule has means of handling expressions like '2x'. At least the docs show:(again in a
isympysession):So it does handle your example, but I don't know enough of
asciimatchto know how much else works.That page also talks about a
LaTeXparser, https://docs.sympy.org/latest/modules/parsing.html#experimental-latex-parsing