示例#1
0
def convert(S):
    '''
    materialize to ArrayStack
    '''
    opStack = ArrayStack()
    answer = ''

    for c in S:
        if c not in "*/+-()":
            answer += c
        elif c == '(':
            opStack.push(c)
        elif c == ")":
            while opStack.peek() != "(":
                answer += opStack.pop()
            opStack.pop()
        elif (not opStack.isEmpty()) and prec.get(c) <= prec.get(
                opStack.peek()):
            answer += opStack.pop()
            opStack.push(c)
        else:
            opStack.push(c)

    while not opStack.isEmpty():
        answer += opStack.pop()

    return answer
示例#2
0
def infixToPostfix(tokenList: list) -> list:
    '''
    Algoritms Architecture

    1) 피연산자이면 그냥 출력
    2) '('이면 스택에 push
    3) ')' 이면 '('이 나올때 까지 스택에서 pop, 출력
    4) 연산자이면 스택에서 이보다 높(거나 같)은 우선순위 것들을 pop, 출력
    그리고 이 연산자는 스택에 push
    5) 스택에 남아 있는 연산자는 모두 pop, 출력.
    '''
    prec = {
        '*': 3, '/': 3,
        '+': 2, '-': 2,
        '(': 1,
    }

    opStack = Stack()
    postfixList = []

    for token in tokenList:
        if type(token) is int:
            postfixList.append(token)
        else:
            if opStack.isEmpty() and token in prec.keys():
                opStack.push(token)
            elif token == '(':
                opStack.push(token)
            elif token == ')':
                while opStack.peek() != '(':
                    postfixList.append(opStack.pop())
                opStack.pop()
            elif prec.get(opStack.peek()) < prec.get(token):
                opStack.push(token)
            else:
                postfixList.append(opStack.pop())
                opStack.push(token)
        
    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return postfixList