Example #1
0
def postExp(aStr):
    opStack = Stack()
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 1
    prec["("] = 0
    tokenStr = aStr.split()
    postExpressen = []
    for token in tokenStr :
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token.isdigit():
            postExpressen.append(token)
        elif token == "(" :
            opStack.push(token)
        elif token == ")" :
            token = opStack.pop()
            while token != "(":
                postExpressen.append(token)
                token = opStack.pop()
        else:
            # operator
            while opStack.isEmpty() == False and \
                prec[opStack.peek()] >= prec[token] :
                postExpressen.append(opStack.pop())
            opStack.push(token)
    while not opStack.isEmpty():
        postExpressen.append(opStack.pop())
    endRes = ' '.join(postExpressen)
    print(endRes)
    return endRes
Example #2
0
def infixToPostfit(infixexpr):
    # 记录操作符优先级
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    # 解析表达式到单词列表
    tokenList = infixexpr.split()
    #print(tokenList)
    
    for token in tokenList:
        if token in "+-*/":
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            postfixList.append(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())   # 操作符
    return " ".join(postfixList)    # 合成后缀表达式
Example #3
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        import pdb
        pdb.set_trace()
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == "(":
            opStack.push(token)
        elif token == ")":
            topToken = opStack.pop()
            while topToken != "(":
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)
Example #4
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    #tokenList = infixexpr.split()
    tokenList = [char for char in infixexpr]  # DA_20_20 mod
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        elif token != " ":  # not affected by spaces now. # DA 20_20 mod
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
def infixToPostfix(infixQuery, term):
    queryList = infixQuery.split()
    queryStack = Stack()
    postfixQuery = []
    precOperator = {}
    precOperator["not"] = 4
    precOperator["and"] = 3
    precOperator["or"] = 2
    precOperator["("] = 1

    for query in queryList:
        if query in term:
            postfixQuery.append(query)
            indexNext = queryList.index(query) + 1
            if indexNext != len(queryList) and (queryList[indexNext] in term):
                queryStack.push("and")
        elif query == '(':
            queryStack.push(query)
        elif query == ')':
            stackTeratas = queryStack.pop()
            while stackTeratas != '(':
                postfixQuery.append(stackTeratas)
                stackTeratas = queryStack.pop()
        else:
            while (queryStack.isEmpty() != True) and (
                    precOperator[queryStack.peek()] >= precOperator[query]):
                postfixQuery.append(queryStack.pop())
            queryStack.push(query)

    while (queryStack.isEmpty() != True):
        postfixQuery.append(queryStack.pop())

    return postfixQuery
Example #6
0
def infixToPostfix(expression):

    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    tempStack = Stack()
    postfixList = []
    tokenList = expression.split()
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":

            postfixList.append(token)
        elif token == "(":
            tempStack.push(token)
        elif token == ")":
            toptoken = tempStack.pop()
            while toptoken != '(':
                postfixList.append(toptoken)
                toptoken = tempStack.pop()
        else:
            while (not tempStack.isEmpty()) and (prec[tempStack.peek()] >= prec[token]):
                postfixList.append(tempStack.pop())
            tempStack.push(token)

    while not tempStack.isEmpty():
        postfixList.append(tempStack.pop())

    return " ".join(postfixList)
Example #7
0
def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0

    while index < len(symbolString) and balanced:
        symbol = symbolString[index]

        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()

                if not matches(top, symbol):
                    balanced = False

        index = index + 1

    if balanced and s.isEmpty():
        return True
    else:
        return False
def infix_to_postfix(infix_expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    op_stack = Stack()
    postfix_list = []
    token_list = infix_expr.split()

    for token in token_list:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfix_list.append(token)
        elif token == '(':
            op_stack.push(token)
        elif token == ')':
            top_token = op_stack.pop()
            while top_token != "(":
                postfix_list.append(top_token)
                top_token = op_stack.pop()
        else:
            while (not op_stack.isEmpty()) and \ (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
                op_stack.push(token)

    while not op_stack.isEmpty():
        postfix_list.append(op_stack.pop())
    return " ".join(postfix_list)
Example #9
0
def infixToPostfix(infixexpr):
    #记录操作符优先级
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    opStack = Stack()  #保存运算符
    postfixList = []  #保存结果
    tokenList = infixexpr.split()  #解析表达式到单词列表

    for token in tokenList:
        if token in string.ascii_uppercase:  #操作数
            postfixList.append(token)
        elif token == "(":
            opStack.push(token)
        elif token == ")":
            topToken = opStack.pop()
            while topToken != "(":
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:  #操作符
            while (not opStack.isEmpty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())  #操作符

    return " ".join(postfixList)  #合成后缀表达式字符串
Example #10
0
def infix_to_postfix(exp):
    stack = Stack()
    result = ""
    priority = {'^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, '(': 0}

    for i in exp:
        # if alnum, then add to the result string
        if i.isalnum():
            result += i
        # if (, then push it to the stack
        elif i == "(":
            stack.push(i)
        # if ) then, pop all the elements till you encounter (, including (
        elif i == ")":
            while stack.peek() != "(":
                result += stack.pop()
            stack.pop()
        # if it's an operator, pop until the rank of the op in stack is >= the current op
        else:
            while not stack.isEmpty() and priority[
                    stack.peek()] >= priority[i]:
                result += stack.pop()
            stack.push(i)

    # pop all the remaining elements to result
    while not stack.isEmpty():
        result += stack.pop()

    return result
Example #11
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    opStack = Stack()
    postfixList = []

    tokenList = infixexpr.split()

    for token in tokenList:
        if token in string.ascii_uppercase:
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)
def infixToPostfix(infixexpr):
    prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    opStack = Stack()
    postfixList = []
    try:
        tokenList = infixexpr.split()
        for token in tokenList:
            if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
                postfixList.append(token)
            elif token == '(':
                opStack.push(token)
            elif token == ')':
                topToken = opStack.pop()
                while topToken != '(':
                    postfixList.append(topToken)
                    topToken = opStack.pop()
            else:
                while (not opStack.isEmpty()) and \
                        (prec[opStack.peek()] >= prec[token]):
                    postfixList.append(opStack.pop())
                opStack.push(token)
    except:
        return f"Incorrect object type for infix expression.{TypeError}"

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Example #13
0
def infixToPrefix(infixexpr):
    exprList = infixexpr.split(' ')
    exprList.reverse()
    output = []
    opStack = Stack()

    for token in exprList:
        if token == ')':
            opStack.push(token)
        elif token == '(':  # pop until find the left-parenthesis.
            while True:
                op = opStack.pop()
                if op == ')':
                    break
                else:
                    output.append(op)
        elif token in ['+', '-', '*', '/']:
            # pop superior or equal operators then push operator.
            # do not pop `)` here.
            while not opStack.isEmpty() and opStack.peek() != ')':
                if isSuperiorOrEqual(opStack.peek(), token):
                    output.append(opStack.pop())
                else:
                    break
            opStack.push(token)
        else:
            output.append(token)

    # retrieve the remain marks in operation stack.
    while not opStack.isEmpty():
        output.append(opStack.pop())

    output.reverse(
    )  # output is a reverse of prefix as a result of beginning reverse operation.
    return ' '.join(output)
def infix2postfix(infix):
    prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1}

    opStack = Stack()
    postfixLst = []

    token_lst = infix.split()

    for token in token_lst:
        if token in string.ascii_uppercase:
            postfixLst.append(token)

        elif token == '(':
            opStack.push(token)

        elif token == ')':
            topToken = opStack.pop()
            while topToken != "(":
                postfixLst.append(topToken)
                topToken = opStack.pop()

        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                               prec[token]):  # peek可看顶端元素
                postfixLst.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixLst.append(opStack.pop())

    return " ".join(postfixLst)
Example #15
0
def infixToPostfix(infixexpr):
    #Specify the dictionary with precedence
    #Create a stack to keep operators.
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in ('+', '-', '*', '/', '%'):
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            postfixList.append(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
def infixToPostfix(infixexpr):
    prec = {}
    prec["**"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = tokenize(infixexpr)
    

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
def tranfortExpress(expression):
    priority = {}
    priority["/"] = 3
    priority["*"] = 3
    priority["+"] = 2
    priority["-"] = 2
    priority["("] = 1

    emptyStack = Stack()
    emptyList = []

    tokenList = expression.split()

    for token in tokenList:
        if token in string.ascii_uppercase:
            emptyList.append(token)
        elif token == '(':
            emptyStack.push(token)
        elif token == ')':
            topToken = emptyStack.pop()
            while topToken != '(':
                emptyList.append(topToken)
                topToken = emptyStack.pop()
        else:
            while (not emptyStack.isEmpty()) and \
                    (priority[emptyStack.peek()] >= priority[token]):
                emptyList.append(emptyStack.pop())
            emptyStack.push(token)
    while not emptyStack.isEmpty():
        emptyList.append(emptyStack.pop())

    return ' '.join(emptyList)
Example #18
0
def infix_to_postfix(infix_expr):
    """
    Convert an infix mathematical expression into an postfix expression.
    :param infix_expr: String of infix expression
    :return: original infix expression as a postfix expression
    """
    prec = {"**": 4, "//": 3, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    op_stack = Stack()  # Stack to hold operators
    postfix_list = []  # Where we will insert our postfix expression to print
    token_list = []
    tmp_str = ''
    operator_str = ''
    for ch in infix_expr:  # Convert expression into a list  3.0*5 + 4
        if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or ch in "0123456789.":
            if operator_str != '':
                token_list.append(operator_str)
                operator_str = ''
            tmp_str = tmp_str + ch
        elif ch in "*+/-":
            if tmp_str != '':
                token_list.append(tmp_str)
                tmp_str = ''
            operator_str = operator_str + ch
        elif ch in "()":
            if tmp_str != '':
                token_list.append(tmp_str)
                tmp_str = ''
            elif operator_str != '':
                token_list.append(operator_str)
                operator_str = ''
            token_list.append(ch)
    if tmp_str != '':
        token_list.append(tmp_str)
    if tmp_str != '':
        token_list.append(operator_str)

    for token in token_list:  # Go through each item in the list.
        if token not in "+-**//()":
            postfix_list.append(token)  # add expression to list, not operator
        elif token == '(':  # Notify that we'll have an operator of top priority coming up
            op_stack.push(token)
        elif token == ')':
            top_token = op_stack.pop()
            while top_token != '(':  # Take the operator out of the stack and insert into our pfix list
                postfix_list.append(
                    top_token)  # continue for as many tokens were in the ()
                top_token = op_stack.pop()
        elif token == '':
            pass
        else:
            while (not op_stack.isEmpty()) and \
                    (prec[op_stack.peek()] >= prec[token]):  # compare operator precedence, decide which goes first
                postfix_list.append(op_stack.pop())
            op_stack.push(token)

    while not op_stack.isEmpty():
        postfix_list.append(op_stack.pop())
    return " ".join(postfix_list)
Example #19
0
def infixToPostfixEval(expr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    opStack = Stack()
    operandStack = Stack()
    postfixList = []
    tokenList = expr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789!":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                               prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    str = " ".join(postfixList)
    tokenList2 = str.split()

    for token in tokenList2:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            return "Cannot be evaluated"
        elif token in "0123456789":
            operandStack.push(int(token))
        elif token == '!':
            operand = operandStack.pop()
            result = math.factorial(operand)
            operandStack.push(result)
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)

    x = str, "Evaluates to: ", operandStack.pop()

    return x
Example #20
0
def infixToPostfixEval(infixExpre):
    prec = {}
    prec["!"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixExpre.split()

    #infix to postfix
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    postfixExpre = (" ".join(postfixList))

    #postfix to eval
    operandStack = Stack()
    tokenList = postfixExpre.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        #seperate statements for factorial
        elif token == "!":
            operand1 = operandStack.pop()
            result = doFactorial(operand1)
            operandStack.push(result)
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)

    return postfixExpre, operandStack.pop()
def parChecker(str):
    s = Stack()
    for char in str:
        if char == '(':  # when encounter a left-parenthesis, push it to a stack.
            s.push(char)
        elif char == ')':  # when encounter a right-parenthesis,
            #  if the stack is empty, it means no matching left parenthesis.
            if s.isEmpty():
                return False
            else:
                s.pop(
                )  # a right parenthesis can offset a left parenthesis in the stack.
    return s.isEmpty(
    )  # finally, if the stack is clear, all parentheses match.
Example #22
0
def balance_brackets(string):
    stack = Stack()
    open = "([{"
    close = ")]}"

    for i in string:
        if i in open:
            stack.push(i)
        else:
            if stack.isEmpty() or open.index(stack.peek()) != close.index(i):
                return False
            stack.pop()

    return stack.isEmpty()
Example #23
0
def infixToPostfit(infixexpr):
    # 记录操作符优先级
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    # 解析表达式到单词列表
    tokenList = infixexpr.split()
    #print(tokenList)
    '''
    for token in tokenList:
        # 这样识别有一个 bug,只能识别单个数字和字母,两位数及其以上都不行
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:   # 操作符
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)
    '''
    for token in tokenList:
        if token in "+-*/":
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            postfixList.append(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())  # 操作符
    return " ".join(postfixList)  # 合成后缀表达式
Example #24
0
def infixToPostfixEval(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["!"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()
    output: ""

    for token in tokenList:
        if token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            topToken = opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
                (prec[opStack.peek()] >= prec[token]):
                   postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
        output = " ".join(postfixList)
        operandStack = Stack()
        str1 = " ".join(postfixList)
        tokenLists = str1.split()

        for token in tokenLists:
            if token in "0123456789":
                operandStack.push(int(token))
            else:
                if token == "!":
                    result = math.factorial(operandStack.pop())

                else:
                    operand2 = operandStack.pop()
                    operand1 = operandStack.pop()
                    result = doMath(token, operand1, operand2)
                operandStack.push(result)
        return output, operandStack.pop()
Example #25
0
def parChecker(symbolString):
    s = Stack()
    balance = True
    for each in symbolString:
        if each == '(':
            s.push(each)
        else:
            if s.isEmpty():
                balance = False
            else:
                s.pop()
    if s.isEmpty() and balance:
        return True
    else:
        return False
Example #26
0
def infixToPostfix(infix):
    #infix = '(' + infix + ')'
    #Initialize Stack.
    opStack = Stack()
    output = ""
    #print(infix)
    #Loop Through All Tokens:
    for token in infix:
        #Case 1: Operator.
        if (isOperator(token)):
            while (not (opStack.isEmpty()) and isOperator(opStack.peek()) and (
                (getAssociativity(token) == 'L'
                 and getPrecedence(opStack.peek()) >= getPrecedence(token)) or
                (getAssociativity(token) == 'R'
                 and getPrecedence(opStack.peek()) > getPrecedence(token)))):
                output += opStack.peek()
                opStack.pop()
            opStack.push(token)
        #Case 2: Left Paranthesis.
        elif (token == '('):
            opStack.push(token)
        #Case 3: Right Paranthesis.
        elif (token == ')'):
            while (not (opStack.isEmpty()) and opStack.peek() != '('):
                output += opStack.peek()
                opStack.pop()
            #Error-Checking:
            if (opStack.isEmpty()):
                # print("Empty Stack.")
                print(output)
                # return "ERROR"
            if (opStack.peek() == '('):
                opStack.pop()
        else:
            #Check For Non-Alpha Characters:
            if (not (token.isalpha())):
                # print("Not Alpha Not Space:", token, ".")
                return "ERROR"
            output += token
    #Append All Remaining Characters From opStack.
    while (not (opStack.isEmpty())):
        if (opStack.peek() == '(' or opStack.peek() == ')'):
            # print("Uh-OH! Mismatched Paranthesis")
            return "ERROR"
        output += opStack.peek()
        opStack.pop()
    #Return Output.
    return output
Example #27
0
def parChecker(symbolString):
    s = Stack()

    for i in symbolString:
        if i == '(':
            s.push(i)
        elif i == ')':
            if s.isEmpty():
                return "Unbalanced"
            else:
                s.pop()

    if s.isEmpty():
        return "Balanced"
    else:
        return "Unbalanced"
def divideBy2(decNumber):
    '''
    将整数不断除以 2,每次得到的余数就是由低到高的二进制
    即最早得到余数,反而最后输出(把余数分别输出,而不是作为一个整体输出)
    而起把数字变成字符处理,会简单些,输出是字符,不是数字
    操作步骤:
    1) 先建立一个空栈
    2) 把十进制数除以 2 得到的余数进栈
    3) 并把十进制数更新为除以 2 的商
    4) 重复 2, 3 步骤, 直到十进制数为零为止
    5) 出栈即可

    实际操作中,因为把该功能使用函数实现,因此要返回一个值
    所以要把栈中的数,输出后拼接在一起,再作为函数的返回值
    而拼接使用字符拼接更为方便,字符相加即可,
    故要把栈中数转换为字符
    '''
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString
Example #29
0
def build_parse_tree(expr: str):
    """构建一棵解析树

    expr: 全括号的算数表达式,运算符与数字之间用括号隔开

    :param expr: str
    :return: BinaryTree
    """
    ope_ls = expr.split()
    node_stack = Stack()
    tree = BinaryTree('')
    for e in ope_ls:
        if e == '(':
            tree.left_child = BinaryTree('')
            node_stack.push(tree)
            tree = tree.left_child
        elif e in "+-*/":
            tree.root = e
            tree.right_child = BinaryTree('')
            node_stack.push(tree)
            tree = tree.right_child
        elif e.isdigit():
            tree.root = int(e)
            tree = node_stack.pop()
        elif e == ")":
            if node_stack.isEmpty():
                return tree
            tree = node_stack.pop()
Example #30
0
def direct_infix_evaluator(infixexpr: str) -> int or float:
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixEvaluation = Stack()
    tokenList = infixexpr.split()
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixEvaluation.push(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            found = False
            while topToken != '(' and not opStack.isEmpty():
                found = True
                operator = topToken
                operand2 = postfixEvaluation.pop()
                operand1 = postfixEvaluation.pop()
                postfixEvaluation.push(doMath(operator, operand1, operand2))
                topToken = opStack.pop()
            if not found:
                raise Exception('Unbalanced parentheses,too much ")"')
        else:
            while (not opStack.isEmpty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                operator = opStack.pop()
                operand2 = postfixEvaluation.pop()
                operand1 = postfixEvaluation.pop()
                postfixEvaluation.push(doMath(operator, operand1, operand2))
            opStack.push(token)
    unbalanced_found = False
    while not opStack.isEmpty():
        last = opStack.pop()
        if last == '(':
            unbalanced_found = True
            raise Exception('Unbalanced parentheses,too much "("')
        operator = last
        operand2 = postfixEvaluation.pop()
        operand1 = postfixEvaluation.pop()
        postfixEvaluation.push(doMath(operator, operand1, operand2))
    return postfixEvaluation.pop()
def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol)
        else: 
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.isEmpty():
        return True
    else:
        return False
def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString
def toStr(n, base):
    convertString = '0123456789ABCDEF' # can cover base upto 16
    rStack = Stack()
    while n >0:
        if n<base:
            rStack.push(convertString[n])
        else:
            rStack.push(convertString[n % base])
        n= n // base
    res = ''
    while not rStack.isEmpty():
        res = res + rStack.pop()
    return res
def parChecker(symbolString):
    s = Stack()

    balanced = True
    index = 0

    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                       balanced = False

        index = index + 1

    if balanced and s.isEmpty():
        return True
    else:
        return False
def baseConverter(decNumber, base):
    digits = "0123456789ABCDEF"

    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % base
        remstack.push(rem)
        decNumber = decNumber // base

    newString = ""
    while not remstack.isEmpty():
        newString = newString + digits[remstack.pop()]

    return newString