My task is to take in a math operation in the form of a string and return the answer as an integer. Order of operations is also ignored and the math operation has to be solved left to right.
My code could probably be shorter/simpler, but this is what I've come up with. My strategy is to go through each character in the string until I hit an operator(+,-,x,/). Then the string of numbers before the operator is turned into an integer. The operator is stored as the variable c
so that the operation can be done with the current number and the next number encountered(c=1 refers to addition, etc.).
When I run the program, it's supposed to print the variable total
, but doesn't print anything. Do the return
statements exit out of the current if
statement or do they exit out of the while
loop? Is the problem something else?
def compute(e):
a=0 #starting index used to check specific characters in string
b=0 #to keep track of index after last operator
l=len(e) #length of e to use for while loop
st=""
total=0 #result of all previous calculations
count=0 #keeps track of number of operators passed
c=0 #Used to keep track of what operator was last passed
#c=1 is addition
#c=2 is subtraction
#c=3 is multiplication
#c=4 is division
while l>0:
if e[a].isdigit():
return
elif e[a]=="+" or e[a]=="-" or e[a]=="x" or e[a]=="/": #When an operator is detected in string
st=e[b:a] #To combine all numbers between two operators into one string
count=count+1 #to keep track of number of operators passed
b=a+1 #now b is the index after the last operator
if count==1: #This is the first operator encountered in string
total=int(st) #The string is stored as total because this is the first integer stored
else:
num=int(st) #The string of numbers is stored as num instead of total
if count==1: #This means this is the first operator and there should not be an operation done yet
return
elif c==1:
total=total+num
elif c==2:
total=total-num
elif c==3:
total=total*num
elif c==4:
total=total/num
if e[a]=="+":
c=1
elif e[a]=="-":
c=2
elif e[a]=="x":
c=3
elif e[a]=="/":
c=4
else:
return None
a=a+1
l=l-1
print(total)
compute("22-11x4")
input("Wait")