从JSON数据解释Python函数 [英] Interpreting a Python function from JSON data

查看:131
本文介绍了从JSON数据解释Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定通过json传递给python的两个简单函数的等效性,就像这样:

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)

我的假设是结果返回false,因为响应和答案被解释为字符串.我该如何比较这两个函数,就像我在python中那样设置变量一样:

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

推荐答案

您需要将字符串转换为SymPy表达式:

You need to convert the strings into SymPy expressions:

sympify(answer) == sympify(response)

这篇关于从JSON数据解释Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆