0

What are some approaches to evaluate an expression such as ((1 + 1) * 2) - 3? Right now I am converting it to postfix form 1 1 + 2 * 3 - and then evaluate that one. I'd like to know if there are better approaches than this.

NepNep
  • 274
  • 1
  • 2
  • 6
  • 1
    Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Trenton McKinney Jun 19 '20 at 16:00
  • @TrentonMcKinney, no, those answers pointed me to use other libraries to evaluate the expression. Here I'd like to know some ways to implement a simple python eval() function. – NepNep Jun 19 '20 at 16:04

1 Answers1

0

This should work, but the Expression must be between parentheses for example : ((4-6)+(7/9)+3) should be (((4-6)+(7/9))+3)

def evalu(express):
    operat,numbers=[],[]
    for i in express:
        if i =='(':
            pass
        elif i in '0123456789':
            numbers.append(int(i))
        elif i in "+*-/":
            operat.append(i)
        elif i==")" :
            oper=operat.pop()
            if oper =='+':numbers.append(numbers.pop()+numbers.pop())
            elif oper =='*':numbers.append(numbers.pop()*numbers.pop())
            elif oper =='/':numbers.append(numbers.pop(-2)/numbers.pop())
            elif oper =='-':numbers.append(numbers.pop(-2)-numbers.pop())
    return numbers.pop()
HichamMtn
  • 11
  • 2