0

I wrote piece of code that takes an equation from the user and evaluate the right hand side and the left hand side separately to check if the equation is balanced. If there is an undefined variable it catches a NameError exception. I want to modify that to check if only on variable is not defined in the dictionary I want the program to solve for that variable and add it to the dictionary. How can I do that? Here is my code

eq=input("Enter an equation")
answer=eq.split("=")
lhs=answer[0]
rhs=answer[1] 
try:
    rhs_value=eval(rhs,dict)
    lhs_value=eval(lhs,dict)
except NameError:
    print("Undefiened varaible")
else:
    if(rhs_value==lhs_value):
        print("Your equation is correct")
    else:
        print("Your equation is incorrect")

let's say the user enters Vs=(-5*g)+Vs. g is defined in dict but not Vs. I want it to solve for Vs and add it to the dictionary. but if both variables are undefined it would print something like too many variables to solve for

user3043108
  • 965
  • 1
  • 8
  • 10
  • Could you add a couple of examples of the desired behabiour? I don't understand what should happen if (say) you have 2 undefined variables, or whether it matters if the undefined variable is in the left or the right side of the equation – Mateo Torres Dec 02 '20 at 01:23

1 Answers1

0

If I understood your question correctly, this should help you detect up to 1 undefined variable, and account for it:

import re
# Here I define some globals for the eval
defined_variables = {
    'g':0
}
# the expression is hardcoded in my code, but this is essentially equivalent to input()
expression = 'Vs=(-5*g)+Vs'
lhs, rhs = expression.split('=')
name_error_count = 0
while name_error_count <= 1:
    try:
        lhs_value = eval(lhs, defined_variables)
        rhs_value = eval(rhs, defined_variables)
    except NameError as e:
        name_error_count += 1
        if name_error_count > 1:
            print("Too many undefined variables")
            raise
        else:
            print(e)
            m = re.search(r"name '(\w+)' is not defined", str(e))
            undefined_variable = m.group(1)
            defined_variables[undefined_variable] = 0 # I assign None here, but you probably need to assign something else or handle this later *
            print(f'Found undefined variable {undefined_variable}, defining')
            continue # we try to get the values again
    # if we reach this point, we know we either had no problems, or at most one undefined variable
    break 
if name_error_count <= 1: # 
    # I would probably try to solve for the undefined variables here
    
    if rhs_value==lhs_value:
        print("Your equation is correct")
    else:
        print("Your equation is incorrect")
Mateo Torres
  • 1,545
  • 1
  • 13
  • 22