human
Program to evaluate simple expressions | A utility function to check if a given character is operand.
utility function to find value of and operand.
This function evaluates simple expressions . It returns - 1 if the given expression is invalid ..
Base Case : Given expression is empty.
The first character must be an operand , find its value.
Traverse the remaining characters in pairs.
The next character must be an operator , and next to next an operand.
If next to next character is not an operand.
Update result according to the operator.
If not a valid operator.
Driver Code"
Solution in Python:
assistant
#Here is code to program to evaluate simple expressions and the other steps required.
 def isOperand ( c ) :
	return ( c >= '0' and c <= '9' ) ;
def value ( c ) :
	return ord ( c ) - ord ( '0' ) ;
def evaluate ( exp ) :
	len1 = len ( exp ) ;
	if ( len1 == 0 ) :
		return - 1 ;
	res = value ( exp [ 0 ] ) ;
	for i in range ( 1 , len1 , 2 ) :
		opr = exp [ i ] ;
		opd = exp [ i + 1 ] ;
		if ( isOperand ( opd ) == False ) :
			return - 1 ;
		if ( opr == ' + ' ) :
			res += value ( opd ) ;
		elif ( opr == ' - ' ) :
			res -= int ( value ( opd ) ) ;
		elif ( opr == ' * ' ) :
			res *= int ( value ( opd ) ) ;
		elif ( opr == ' / ' ) :
			res /= int ( value ( opd ) ) ;
		else :
			return - 1 ;
	return res ;
expr1 = "1 + 2*5 + 3" ;
res = evaluate ( expr1 ) ;
print ( expr1 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr1 , " is " , res ) ;
expr2 = "1 + 2*3" ;
res = evaluate ( expr2 ) ;
print ( expr2 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr2 , " is " , res ) ;
expr3 = "4-2 + 6*3" ;
res = evaluate ( expr3 ) ;
print ( expr3 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr3 , " is " , res ) ;
expr4 = "1 + + 2" ;
res = evaluate ( expr4 ) ;
print ( expr4 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr4 , " is " , res ) ;