Interpreting a Python function from JSON data

▼魔方 西西 提交于 2019-12-12 00:49:55

问题


I am trying to determine the equivalence of two simple functions passed to python via json like so:

PHP:

$data = array("2*x", "x*2");
$result = shell_exec('python /path/check.py ' . escapeshellarg(json_encode($data)));

Python:

import sys, json
from sympy import *

try:
    data = json.loads(sys.argv[1])
except:
    sys.exit(1)

x = Symbol('x')

response = data[0]
answer = data[1]

result = response==answer

print json.dumps(result)

My assumption is that result returns false because the response and answer are being interpreted as strings. How can I compare these two functions as if I set the variables in python like so:

response = 2*x
answer = x*2

回答1:


You need to convert the strings into SymPy expressions:

sympify(answer) == sympify(response)


来源:https://stackoverflow.com/questions/55931761/interpreting-a-python-function-from-json-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!