As part of an assignment, I am creating a function that takes in a string, which is an equation. here is an example of one: 48+6x6/3=6x8-9x2. The compute function takes one side of the equal sign and evaluates it. I am not too concerned with splitting the equation. I believe I can just slice it with s[:s.find("=")]
.
My main problem is the compute function itself. I will post where I am with it so far. The commented out part was stuff I was trying to deal with double digits but I cannot figure out a logical way to do that. I would like some help thinking about this.
I was told not to use eval because doing eval on an equation "2+3*5-11/2*88+153" would not be easy due to operator precedence--or lack thereof. My program should not obey the normal operator precedence rules. Instead it is supposed to evaluate purely from left to right.
def compute(s):
result = 0
a = 1
for a in range(len(s)):
#while s[a].isdigit():
#result = (result * 10) + int(s[a])
#a += 1
if s[a] == '/':
result = result / int(s[a + 1])
elif s[a] == '+':
result = result + int(s[a + 1])
elif s[a] == 'x' or s[a] == '*' or s[a] == 'X':
result = result * int(s[a + 1])
elif s[a] == '-':
result = result - int(s[a + 1])
else:
result += int(s[a])
a += 1
return result
print(compute("48+6x6/3") == 108)
EDIT this works for single digits. Maybe we can get this to work with multiple digits
def compute(s):
result = int(s[0])
op = 0
a = 1
while a < len(s):
if s[a] == '/':
result /= int(s[a + 1])
elif s[a] == '+':
result += int(s[a + 1])
elif s[a] == '*':
result *= int(s[a + 1])
elif s[a] == '-':
result -= int(s[a + 1])
a += 1
return int(result)