In: Computer Science
Write A function with an input parameter which is a string arithmetic statement which contains only alphabet variables and binary operations including +, -, *, / and % and checks whether the statement is a valid arithmetic statement or not. If the statement is valid, the function returns true, otherwise returns false. • The statement might contain parenthesis as well. For instance: • a+b*a+c/c%y • (a+b)*(a/d-(a/b)) • You can make this assumption that the variable names contain only one alphabet (like a, b, c) and cannot have more than one alphabets (like ab, temp, sum, ….). Write a python program for this question. Do not use append. Use the main function and also provide the output with the program as well.
please check out the code with the output... the code is concedered with each and every edge cases possible... for any doubt, please leave a comment... thank you
code
def expr(str):
for i in range(0,len(str)-1): #checking if the variables are of single alphabet or not
if(str[i].isalpha() and str[i+1].isalpha()): return False #if not then return False
for i in range(0,len(str)): #checking if there are any other character except alphabet and the binary operator
if (not (str[i].isalpha()) and str[i]!='+'and str[i]!='-'and str[i]!='*'and str[i]!='/'and str[i]!='%' and str[i]!='(' and str[i]!=')'):
return False #if there exist, then return false
count=0 #count is for counting the parenthesis
for i in range(0,len(str)):
if(str[i]==')'):
count+=1 #for ) count increases
if(count>0): #.e. if there is a ) before (
return False
if(str[i]=='('):
count-=1 #for ( count decreases
if(count != 0): return False #if no of ( != no of )
for i in range (0,len(str)-1):
if(str[i]=='+'or str[i]=='-'or str[i]=='*'or str[i]=='/'or str[i]=='%' ):
if(str[i+1]=='+'or str[i+1]=='-'or str[i+1]=='*'or str[i+1]=='/'or str[i+1]=='%' ): #i.e. if there is consecutive two operator
return False
if (str[0]=='+'or str[0]=='-'or str[0]=='*'or str[0]=='/'or str[0]=='%' or str[len(str)-1]=='+'or str[len(str)-1]=='-'or str[len(str)-1]=='*'or str[len(str)-1]=='/'or str[len(str)-1]=='%'):
return False #if the expression starts or ends with operator
return True #else return true
def main(): #main
str=input("Enter expression : ") #input expression
if(expr(str)): ##calling function
print ("The expression is correct")
else:
print ("The expression is not correct")
if __name__=="__main__":
main() #calling main
output...
screen sort of code