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
def isOperand ( c ) : NEW_LINE INDENT return ( c >= '0' and c <= '9' ) ; NEW_LINE DEDENT def value ( c ) : NEW_LINE INDENT return ord ( c ) - ord ( '0' ) ; NEW_LINE DEDENT def evaluate ( exp ) : NEW_LINE INDENT len1 = len ( exp ) ; NEW_LINE if ( len1 == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT res = value ( exp [ 0 ] ) ; NEW_LINE for i in range ( 1 , len1 , 2 ) : NEW_LINE INDENT opr = exp [ i ] ; NEW_LINE opd = exp [ i + 1 ] ; NEW_LINE if ( isOperand ( opd ) == False ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( opr == ' + ' ) : NEW_LINE INDENT res += value ( opd ) ; NEW_LINE DEDENT elif ( opr == ' - ' ) : NEW_LINE INDENT res -= int ( value ( opd ) ) ; NEW_LINE DEDENT elif ( opr == ' * ' ) : NEW_LINE INDENT res *= int ( value ( opd ) ) ; NEW_LINE DEDENT elif ( opr == ' / ' ) : NEW_LINE INDENT res /= int ( value ( opd ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT expr1 = "1 + 2*5 + 3" ; NEW_LINE res = evaluate ( expr1 ) ; NEW_LINE print ( expr1 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr1 , " is " , res ) ; NEW_LINE expr2 = "1 + 2*3" ; NEW_LINE res = evaluate ( expr2 ) ; NEW_LINE print ( expr2 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr2 , " is " , res ) ; NEW_LINE expr3 = "4-2 + 6*3" ; NEW_LINE res = evaluate ( expr3 ) ; NEW_LINE print ( expr3 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr3 , " is " , res ) ; NEW_LINE expr4 = "1 + + 2" ; NEW_LINE res = evaluate ( expr4 ) ; NEW_LINE print ( expr4 , " is ▁ Invalid " ) if ( res == - 1 ) else print ( " Value ▁ of " , expr4 , " is " , res ) ; NEW_LINE