Advertisement
colinm86

Untitled

Oct 14th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.05 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["*"] = 4
  32.     prec["*"] = 3
  33.     prec["/"] = 3
  34.     prec["//"] = 3
  35.     prec["+"] = 2
  36.     prec["-"] = 2
  37.     prec["("] = 1
  38.     opStack = Stack()
  39.     postfixList = []
  40.     tokenList = tokenize(infixexpr)
  41.     if not checkbalance(tokenList):
  42.         raise Exception('Unbalanced parenthesis')
  43.  
  44.     for token in tokenList:
  45.         if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or bool(re.search(r'(\d+)', token)):
  46.             postfixList.append(token)
  47.         elif token == '(':
  48.             opStack.push(token)
  49.         elif token == ')':
  50.             topToken = opStack.pop()
  51.             while topToken != '(':
  52.                 postfixList.append(topToken)
  53.                 topToken = opStack.pop()
  54.         else:
  55.             while (not opStack.isEmpty()) and \
  56.                (prec[opStack.peek()] >= prec[token]):
  57.                   postfixList.append(opStack.pop())
  58.             opStack.push(token)
  59.  
  60.     while not opStack.isEmpty():
  61.         postfixList.append(opStack.pop())
  62.     return " ".join(postfixList)
  63.  
  64. def postfixEval(postfixExpr):
  65.     """Evaluates postfixexpression
  66.    Arguments:
  67.        postfixExpr {String} -- [description]
  68.    Returns:
  69.        {Float}
  70.    """
  71.     if not isinstance(postfixExpr, str):
  72.         raise TypeError('must pass in string')
  73.     operandStack = Stack()
  74.     tokenList = tokenize(postfixExpr)
  75.  
  76.     for token in tokenList:
  77.         if bool(re.search(r'(\d+)', token)):
  78.             operandStack.push(int(token))
  79.         else:
  80.             operand2 = operandStack.pop()
  81.             operand1 = operandStack.pop()
  82.             result = doMath(token,operand1,operand2)
  83.             operandStack.push(result)
  84.  
  85.     return operandStack.pop()
  86.  
  87. def doMath(op, op1, op2):
  88.     """Evaluates 2 operands with operator in param
  89.    Arguments:
  90.        op {String} -- Operator
  91.        op1 {Integer} -- left operand
  92.        op2 {Integer} -- right operand
  93.    """
  94.    
  95.     if not isinstance(op,str) or not isinstance(op1,int) or not isinstance(op2,int):
  96.         raise TypeError('incorrect parameter type')
  97.     dictionary = {
  98.         '**': lambda op1,op2: op1 ** op2,
  99.         '//': lambda op1,op2: op1 // op2,
  100.         '*': lambda op1,op2: op1 * op2,
  101.         '/': lambda op1,op2: op1 / op2,
  102.         '+': lambda op1,op2: op1 + op2,
  103.         '-': lambda op1,op2: op1 - op2
  104.     }
  105.     if op not in dictionary:
  106.         raise ArithmeticError('parameter must be *,/,-,+')
  107.     return dictionary[op](op1, op2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement