python - Identifying variables in equation -
i'm trying create calculator receive input formula , data respective variables.
i trying made user friendly possible, in mind user insert formula , code identify variables in formula.
after program ask values correspond each variable.
and question is: "how can parse string in search of variables?" have able identify things "pi" , trigonometric functions, since variable angle.
is there simple way this?
edit: code have far, first aproach on user execute code. trying evade using eval , exec
from scipy import stats import matplotlib.pyplot plt import numpy np math import* import math recept = "." print("bem vindo calculadora de incertezas com base no metodo monte carlo") formula = input("insira formula desejada:") while (recept != ""): recept = input("defina variaveis de acordo com o exemplo:\n ex: p = (media, desviopadrão)") print (recept) #aproach one: execute code inserted user: user define variables. if(recept != ""): exec(recept) print (exec(formula))
this should started:
>>> import re >>> formula = "p = v*i*cos(2*pi*f)" >>> variables = re.findall('[a-za-z]+' , formula) ['p', 'v', 'i', 'cos', 'pi', 'f'] >>> special = ['cos', 'pi'] >>> variables = [v v in variables if v not in special] ['p', 'v', 'i', 'f']
from here can improve regular expression account more complex variable names (ex: v1)
Comments
Post a Comment