Advertisement
Guest User

Python Infix Calculator

a guest
Sep 22nd, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | None | 0 0
  1. import re
  2. import operator
  3.  
  4. def main():
  5.     op_stack = []
  6.  
  7.     val_stack = []
  8.  
  9.     ops = ['*', '/', '+', '-']
  10.    
  11.     precedence = { '*':3, '/':3, '+':2, '-':2, '(': 0}
  12.  
  13.     eval_string = input("Enter an expression: ")
  14.  
  15.     eval_string = eval_string.replace(" ", "")
  16.  
  17.     eval_string = re.split(r'([)(*/+-])', eval_string)
  18.  
  19.     operand = re.compile(r'\d+\.*\d*')
  20.  
  21.     for token in eval_string:
  22.  
  23.         if operand.match(token):
  24.             val_stack.append(float(token))
  25.             print(token)
  26.  
  27.         if token == '(':
  28.             op_stack.append(token)
  29.  
  30.         if token in ops:
  31.             while len(op_stack) > 0 and precedence[token] <= precedence[op_stack[-1]]:
  32.                 op = op_stack.pop()
  33.                 do_op(op, val_stack)
  34.  
  35.             op_stack.append(token)
  36.  
  37.         if token == ')':
  38.             while len(op_stack) > 0 and op_stack[-1] != '(':
  39.                 op = op_stack.pop()
  40.                 do_op(op, val_stack)
  41.                
  42.             op_stack.pop()
  43.  
  44.     while len(op_stack) > 0:
  45.             op = op_stack.pop()
  46.             do_op(op, val_stack)
  47.  
  48.     print(val_stack.pop())
  49.  
  50. def do_op(op, val_stack):
  51.     function = {'*':operator.mul, '/':operator.truediv, '+':operator.add, '-':operator.sub}
  52.     temp = val_stack.pop()
  53.     val_stack.append(function[op](val_stack.pop(), temp))
  54.  
  55. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement