I am trying to solve a codewar challenge (link):
Your job is to create a calculator which evaluates expressions in Reverse Polish notation.
For example expression
5 1 2 + 4 * + 3 -(which is equivalent to5 + ((1 + 2) * 4) - 3in normal notation) should evaluate to 14.For your convenience, the input is formatted such that a space is provided between every token.
Empty expression should evaluate to 0.
Valid operations are
+,-,*,/.You may assume that there won't be exceptional situations (like stack underflow or division by zero).
I have 2 problems, the first is that the code looks awful and I don't know how to improve it tbh, I also want this code to be able to compute multiple digit numbers and i feel like i need to start from scratch if I want to add that.
Note : This is my first time writing a question so if there's anything wrong with it please tell me and I'll change it.
def calc(expr): stack = [] for i in range(len(expr)): if expr[i].isdigit(): stack.append(expr[i]) if expr[i-1] == '.': stack.pop() if expr[i] == '.': stack.pop() stack.append(expr[i-1] + expr[i] + expr[i+1]) if expr[i] == '+': stack.append(float(stack[-2]) + float(stack[-1])) for i in range(2): del stack[-2] if expr[i] == '-': stack.append(float(stack[-2]) - float(stack[-1])) for i in range(2): del stack[-2] if expr[i] == '*': stack.append(float(stack[-2]) * float(stack[-1])) for i in range(2): del stack[-2] if expr[i] == '/': stack.append(float(stack[-2]) / float(stack[-1])) for i in range(2): del stack[-2] if stack == []: return 0 else: return float(stack[0])