Created
December 22, 2013 16:45
-
-
Save oss6/8085217 to your computer and use it in GitHub Desktop.
A simple parser implemented in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parser: | |
def __init__(self, infix): | |
self.__infix = infix | |
self.__postfix = "" | |
self.__operators = ['+', '-', '*', '/', '^'] | |
def parse(self): | |
self.__infix_to_postfix() | |
return self.__eval_postfix() | |
def __infix_to_postfix(self): | |
stack = [] | |
for e in self.__infix: | |
# OPERAND | |
if e not in self.__operators: | |
self.__postfix += e | |
# OPERATOR | |
else: | |
if not stack: | |
stack.append(e) | |
else: | |
while stack and Parser.__check_precedence(stack[-1], e): # e < stack[-1] | |
self.__postfix += stack.pop() | |
stack.append(e) | |
while stack: | |
self.__postfix += stack.pop() | |
return self.__postfix | |
def __eval_postfix(self): | |
stack = [] | |
for e in self.__postfix: | |
if e not in self.__operators: | |
stack.append(e) | |
else: | |
temp = stack[-1] | |
stack.pop() | |
retVal = Parser.__operation(stack[-1], temp, e) # !!! --> tmp --> topStack(Operator)temp | |
stack.pop() | |
stack.append(retVal) | |
return stack[-1] | |
@staticmethod | |
def __operation(a, b, op): | |
a = float(a) | |
b = float(b) | |
if op == "+": | |
return a + b | |
if op == "-": | |
return a - b | |
if op == "*": | |
return a * b | |
if op == "/": | |
return a / b | |
if op == "^": | |
return a ** b | |
@staticmethod | |
def __check_precedence(op1, op2): | |
if op1 == "^": | |
return True | |
if (op1 == "*" or op1 == "/") and (op2 == "+" or op2 == "-"): | |
return True | |
"""if (op1 == "+" or op1 == "-") and (op2 == "*" or op2 == "/"): | |
return False""" | |
return False | |
def main(): | |
p = Parser("9+1-4*2") | |
print(p.parse()) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment