6/15/2014

Evaluate Math Expression

A hacky way with python is quite simple
print eval('1+ 2*3 - 5', {'__builtins__' : None})

Otherwise, we assume there is not brackets
 #include <iostream>  
 #include <stack>  
 using namespace std;  
 class Eval {  
 public:  
  int operator()(string s) {  
   stack<int> operands;  
   stack<char> operators;  
   int num = 0;  
   for(int i = 0; i < s.length(); ++i) {  
    if(s[i] >= '0' && s[i] <= '9') {  
     num = num * 10 + s[i] - '0';  
    } else if(s[i] == '+' || s[i] == '-') {  
     if(operands.empty()) {  
      operands.push(num);  
     } else {  
      if(!operators.empty() && (operators.top() == '*' || operators.top()=='/')) {  
       if(operators.top() == '*') {  
        operands.top() *= num;  
       } else if(operators.top() == '/') {  
        operands.top() /= num;  
       }  
       operators.pop();  
      }  
     }  
     operators.push(s[i]);  
     num = 0;  
    } else if(s[i] == '*' || s[i] == '/') {  
     operands.push(num);  
     operators.push(s[i]);  
     num = 0;  
    }  
   }  
   operands.push(num);  
   while(operands.size() > 1) {  
    int right = operands.top();  
    operands.pop();  
    int left = operands.top();  
    operands.pop();  
    char op = operators.top();  
    operators.pop();  
    if(op=='+') {  
     left += right;  
    } else if(op=='-') {  
     left -= right;  
    } else if(op=='*') {  
     left *= right;  
    } else if (op=='/') {  
     left /= right;  
    }  
    operands.push(left);  
   }  
   return operands.top();  
  }  
 };  
 int main(int argc, char *argv[])  
 {  
  Eval eval;  
  std::cout << eval("1+2*3 + 5 * 10") << std::endl;  
  return 0;  
 }  

No comments: