Non*_*biz 3 python lambda input scipy argparse
我正在编写一个程序来计算旋转实体的体积.第一步是计算积分.我正在使用scipy.integrate这个,但我无法弄清楚有一个方程的最佳方法(比如x=x**2在命令行输入.我原本打算在以下方面添加一个参数:x | y'然后取出函数作为lambda.不幸的是,argparse不会将lambda作为参数类型,并且尝试使用字符串来构造lambda(f = lambda x: args.equation)只返回一个字符串(实际上可以理解).
这是我到目前为止所得到的:
import sys
import argparse
import math
from scipy import integrate
parser = argparse.ArgumentParser(description='Find the volume of the solid of rotation defined')
parser.add_argument('equation', help='continous function')
parser.add_argument('a', type=float, help='bound \'a\'')
parser.add_argument('b', type=float, help='bound \'b\'')
parser.add_argument('-axis', metavar='x|y', help='axis of revolution')
args = parser.parse_args()
def volume(func, a, b, axis=None):
integral = integrate.quad(func, a, b)
return scipy.py * integral
print volume(args.equation, args.a, args.b)
Run Code Online (Sandbox Code Playgroud)
任何建议将不胜感激
如果让用户运行任意Python代码绝对不担心安全风险,那么您可以使用eval创建可调用对象:
volume(eval('lambda x: %s' % args.equation), args.a, args.b)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
726 次 |
| 最近记录: |