1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
from stack import Stack
class PostfixCalculate:
def __init__(self, origin): self.origin_exp = origin self.postfix_exp = None
def getOpPrec(self,op): if op == '*' or op == '/': return 5 elif op == '+' or op == '-': return 3 elif op == '(': return 1 else: return -1
def convertToPostfix(self): exp_list = [] operate_stack = Stack()
for i in self.origin_exp:
if i.isdigit(): exp_list.append(i) else: if i == '(' or operate_stack.SisEmpty(): operate_stack.SPush(i) elif i == ')': operation = operate_stack.SPop() exp_list.append(operation) elif self.getOpPrec(i) > self.getOpPrec(operate_stack.SPeek()): operate_stack.SPush(i) else:
while not operate_stack.SisEmpty() and self.getOpPrec(i) <= self.getOpPrec(operate_stack.SPeek()): operation = operate_stack.SPop() exp_list.append(operation) operate_stack.SPush(i)
while not operate_stack.SisEmpty(): op = operate_stack.SPop() exp_list.append(op) self.postfix_exp = ''.join(exp_list)
def get_postfix_exp(self): if not self.postfix_exp: self.convertToPostfix()
return self.postfix_exp
if __name__ == '__main__': origin = input("수식을 입력해주세요: ")
calcurate = PostfixCalculate(origin) calcurate.convertToPostfix() print("resutl:", calcurate.get_postfix_exp())
|