import matplotlib.pyplot as plt
import numpy as np
import re
def get_variables(input_string):
count = 0
matches = re.findall(r'(?i)[a-z]', input_string)
return set(matches) #returns unique variables
function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
pattern = r'\b%s\b' %v
function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function
if len(variables) == 1:
plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
ax = plt.axes(projection="3d")
ax.plot3D(*varDict.values(),answer) # line
#ax.scatter3D(*varDict.values(),answer); #scatter
plt.show()
如果您想要散点图或添加逻辑以形成形状(即使用meshgrid),则可以更改3D设置,
只需确保评估语句已完全消毒即可。这也要求该函数在Python语法(** not ^)中输入,除非您要添加函数以编辑字符串中的常见语法差异。
You could try using eval with an inputted X or default x:
import matplotlib.pyplot as plt
import numpy as np
import re
def get_variables(input_string):
count = 0
matches = re.findall(r'(?i)[a-z]', input_string)
return set(matches) #returns unique variables
function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
pattern = r'\b%s\b' %v
function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function
if len(variables) == 1:
plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
ax = plt.axes(projection="3d")
ax.plot3D(*varDict.values(),answer) # line
#ax.scatter3D(*varDict.values(),answer); #scatter
plt.show()
You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)
Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.
发布评论
评论(1)
您可以尝试使用输入的X或默认X来使用评估:
如果您想要散点图或添加逻辑以形成形状(即使用meshgrid),则可以更改3D设置,
只需确保评估语句已完全消毒即可。这也要求该函数在Python语法(** not ^)中输入,除非您要添加函数以编辑字符串中的常见语法差异。
You could try using eval with an inputted X or default x:
You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)
Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.