Identifying variables in equation

482 views Asked by At

I'm trying to create a calculator which will receive as input a formula and the data from the respective variables.

I was trying to made this the most user friendly as possible, so in my mind the user would insert the formula and my code would simply identify the Variables in the formula.

After this the program would simply ask what values correspond to each Variable.

And the question is: "How can I parse the string in search of the variables?" I have to be able to identify things like "pi" and trigonometric functions, since the variable could be the angle.

Is there any simple way to do this?

Edit: This is the code i have so far, it is only my first aproach on which it would be the user to execute the code. But i was trying to evade using eval and exec

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
from math import*
import math
recept = "."

print("Bem vindo a calculadora de incertezas com base no metodo Monte Carlo")
formula = input("Insira a formula desejada:")
while (recept != ""):
    recept = input("Defina as variaveis de acordo com o exemplo:\n EX: P = (media,     desviopadrão)")
    print (recept)

    #Aproach one: Execute code inserted by user: user would define the variables.
    if(recept != ""):
        exec(recept)

print (exec(formula))
2

There are 2 answers

1
elyase On BEST ANSWER

This should get you 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 for v in variables if v not in special]  
['P', 'V', 'I', 'f']

From here you can improve the regular expression to account for more complex variable names (ex: V1)

0
Paul Evans On

You could try RP which gives you a simple parser based on rules you define in EBNF format.