I am writing a Python program that takes a string that is a two sided equation, "(equation) = (equation)", and solves the two sides by blacking out two characters that can be on either side, so that the equations solutions are equal to each other
So far I have this code, and I keep getting the error for any case that is not a one sided equation. Below is the full traceback:
Traceback (most recent call last):
File "C:/Users/rgade_000/Desktop/blackout.py", line 69, in <module>
main()
File "C:/Users/rgade_000/Desktop/blackout.py", line 65, in main
print("+11x4 =",compute("+11x4"), "(expect None)")
File "C:/Users/rgade_000/Desktop/blackout.py", line 22, in compute
temp_num_int = int(temp_num_str)
ValueError: invalid literal for int() with base 10: ''
I know this is a problem at the op == ""
statement, but I don't know how to fix it. The problem only occurs with any string equation that I try to use solve with, for instance with the main call
print("solving 288/24x6=18x13x8: ", solve("288/24x6=18x13x8"))
(The main function contains test cases)
def compute(exp):
"""
Takes a string representing an equation and computes the value
"""
temp_num_str = ""
temp_num_int = 0
op = ""
for ch in exp:
if ch.isdigit():
if temp_num_str == "":
temp_num_str = ch
else:
temp_num_str += ch
else:
if op == "":
op = ch
temp_num_int = int(temp_num_str)
else:
temp_num_int = eqs(temp_num_int, op, temp_num_str)
op = ch
temp_num_str = ""
return eqs(temp_num_int, op, temp_num_str)
def eqs(temp_num_int, op, temp_num_str):
if op == "+":
return temp_num_int + int(temp_num_str)
elif op == "-":
return temp_num_int - int(temp_num_str)
elif op == "x":
return temp_num_int * int(temp_num_str)
else:
return temp_num_int / int(temp_num_str)
def solve(eqn):
"""
Takes two sided equation and blacks out values so that the equations are equal
"""
for i in range(len(eqn)):
for j in range(i+1,len(eqn)):
if i != eqn.find('=') and j != eqn.find('='):
eqn_tmp = eqn[:i] + eqn[i+1:j]+eqn[j+1:]
if evaluate(eqn_tmp) == True:
return eqn_tmp
else:
print("No solution")
def evaluate(eqn):
"""
Evaluates a string of two sided equation and returns True if equal
"""
lt = eqn[:eqn.find('=')]
rt = eqn[eqn.find('=')+1:]
if (compute(lt) == compute(rt)):
return True
else:
return False
def main():
print("22-11x4 =", compute("22-11x4"), " (expect 44)")
print("+11x4 =",compute("+11x4"), "(expect None)")
print("22-11x4=7x5+9", evaluate("22-11x4=7x5+9"),"(expect True)")
print("solving 288/24x6=18x13x8: ", solve("288/24x6=18x13x8"))
main()