Advertisement
colinm86

Untitled

Oct 13th, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.92 KB | None | 0 0
  1. import re
  2. from stack import Stack
  3.  
  4. def tokenize(exp):
  5.     """Takes in a string expression and tokenizes
  6.    Arguments:
  7.        exp {String} -- string expression
  8.    Return:
  9.        {List} - list of expression
  10.    """
  11.     x = re.split(r'(\d+|[a-zA-Z]|[^A-Za-z0-9])', exp)
  12.     return [i for i in x if i.strip()]
  13.  
  14. def checkbalance(tokenlist):
  15.     """Checks if there are balances parenthesis
  16.    Arguments:
  17.        tokenlist {List}
  18.    Reuturns:
  19.        {Boolean}
  20.    """
  21.     return tokenlist.count('(') == tokenlist.count(')')
  22.  
  23. def infixToPostfix(infixexpr):
  24.     """Converts infix expression to postfix expression
  25.    Arguments:
  26.        infixexpr {String}
  27.    Returns:
  28.        postfixexpr {String}
  29.    """
  30.     prec = {}
  31.     prec["*"] = 3
  32.     prec["/"] = 3
  33.     prec["+"] = 2
  34.     prec["-"] = 2
  35.     prec["("] = 1
  36.     opStack = Stack()
  37.     postfixList = []
  38.     tokenList = tokenize(infixexpr)
  39.     if not checkbalance(tokenList):
  40.         raise Exception('Unbalanced parenthesis')
  41.  
  42.     for token in tokenList:
  43.         if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or bool(re.search(r'(\d+)', token)):
  44.             postfixList.append(token)
  45.         elif token == '(':
  46.             opStack.push(token)
  47.         elif token == ')':
  48.             topToken = opStack.pop()
  49.             while topToken != '(':
  50.                 postfixList.append(topToken)
  51.                 topToken = opStack.pop()
  52.         else:
  53.             while (not opStack.isEmpty()) and \
  54.                (prec[opStack.peek()] >= prec[token]):
  55.                   postfixList.append(opStack.pop())
  56.             opStack.push(token)
  57.  
  58.     while not opStack.isEmpty():
  59.         postfixList.append(opStack.pop())
  60.     return " ".join(postfixList)
  61.  
  62. def postfixEval(postfixExpr):
  63.     """Evaluates postfixexpression
  64.    Arguments:
  65.        postfixExpr {String} -- [description]
  66.    Returns:
  67.        {Float}
  68.    """
  69.     if not isinstance(postfixExpr, str):
  70.         raise TypeError('must pass in string')
  71.     operandStack = Stack()
  72.     tokenList = tokenize(postfixExpr)
  73.  
  74.     for token in tokenList:
  75.         if bool(re.search(r'(\d+)', token)):
  76.             operandStack.push(int(token))
  77.         else:
  78.             operand2 = operandStack.pop()
  79.             operand1 = operandStack.pop()
  80.             result = doMath(token,operand1,operand2)
  81.             operandStack.push(result)
  82.  
  83.     return operandStack.pop()
  84.  
  85. def doMath(op, op1, op2):
  86.     """Evaluates 2 operands with operator in param
  87.    Arguments:
  88.        op {String} -- Operator
  89.        op1 {Integer} -- left operand
  90.        op2 {Integer} -- right operand
  91.    """
  92.    
  93.     if not isinstance(op,str) or not isinstance(op1,int) or not isinstance(op2,int):
  94.         raise TypeError('incorrect parameter type')
  95.     dictionary = {
  96.         '*': lambda op1,op2: op1 * op2,
  97.         '/': lambda op1,op2: op1 / op2,
  98.         '+': lambda op1,op2: op1 + op2,
  99.         '-': lambda op1,op2: op1 - op2
  100.     }
  101.     if op not in dictionary:
  102.         raise ArithmeticError('parameter must be *,/,-,+')
  103.     return dictionary[op](op1, op2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement