Ejemplo n.º 1
0
def product_rule(currentNode, currentValue, dStack):
    currentNode.Key = '/'

    gTree = currentNode.getLeftChild()
    dgTree = BinaryTree(currentNode.getLeftChild().key)
    dgNode = dgTree
    iStack = Stack()
    build_tree(currentNode.getLeftChild(), dStack, dgNode, iStack)
    dgTree = derivative(dgTree)

    fTree = currentNode.getRIghtChild()
    dfTree = BinaryTree(currentNode.getRightChild().key)
    dfNode = dfTree
    iStack = Stack()
    build_tree(currentNode.getRightChild(), dStack, dgNode, iStack)
    dfTree = derivative(dfTree)
    prodTree = BinaryTree('+')
    prodNode = quoTree
    prodNode = prodNode.getLeftChild
    prodNode.insertLeft('*')
    prodNode.insertRight('*')
    prodNode = quoNode.getRightChild
    prodNode.insertRight(dgTree)
    prodNode.insertLeft(fTree)
    prodNode = dStack.pop()
    prodNode.getLeftChild()
    prodNode.insertRight(dfTree)
    prodNode.insertLeft(gTree)
    der_output(prodNode)
Ejemplo n.º 2
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
Ejemplo n.º 3
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()
Ejemplo n.º 4
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()
def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in '+-*/)':
            currentTree.setRootVal(eval(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in '+-*/':
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError("Unknown Operator: " + i)
    return eTree
Ejemplo n.º 6
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)
Ejemplo n.º 7
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 buildParseTree(fpexp):
    fplist = format_fpelist(fpexp)
    # fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parrent = pStack.pop()
            currentTree = parrent
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Ejemplo n.º 9
0
def postfixEval(postfixExpr):
    operandStack = Stack()
    # 把后缀表达式以空格分割,并把结果存在列表
    tokenList = postfixExpr.split()
    '''
    # 该代码只能实现 10 以内的运算,10 以上的数字匹配没有
    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)
    '''
    # 修改后,可以实现 10 以上的数字运算
    for token in tokenList:
        if token in "+-*/":
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)
        else:
            operandStack.push(int(token))

    return operandStack.pop()
Ejemplo n.º 10
0
def buildParseTree(fpexp):
####tokenize the expression to follow the rules:
    fplist=fpexp.split()
    pStack=Stack()
    eTree=BinaryTree('')
    pStack.push(eTree)
    currentTree=eTree
    
    for i in fplist:
        if i == '(':
           currentTree.insertLeft('')
           pStack.push(currentTree)
           currentTree=currentTree.getLeftChild()
           
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree=currentTree.getRightChild()
            
         elif i == ')':
             currentTree=pStack.pop()
             
         elif i not in ['+', '-', '*', '/',')']:
            try:
                 currentTree.setRootVal(int(i))
                 parent=pStack.pop()
                 currentTree=parent
            except ValueError:
                 raise ValueError("token '{}' is not a valid interger'.format(i))
                 
       return eTree  
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
def main():
    g = DFSGraph()
    gR = DFSGraph()
    nodeOrd = []
    sccs = []
    scc = []
    s = Stack()

    # Inputs testFile from command line and builds graph g and the reversed graph gR.
    testFile = open(sys.argv[1], 'r')
    for edge in testFile:
        head = edge.split()[0]
        tail = edge.split()[1]
        g.addEdge(head, tail)
        gR.addEdge(tail, head)

    # First pass - builds nodeOrd, the reverse postorder of g.
    DFSGraph.dfs(gR, nodeOrd, sccs, scc)

    # Second pass - builds a list of all SCCs.
    DFSGraph.dfs(g, nodeOrd, sccs, scc)

    # Prints first 10 SCC sizes.
    sccSizes = []
    for scc in sccs:
        sccSizes.append(len(scc))
    sortedSizes = sorted(sccSizes, reverse=True)[:10]
    for i in sortedSizes:
        sys.stdout.write(str(i) + ',')
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)
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)
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
def build_parse_tree(exp_string):
    exp_list = exp_string.split()  # 表达式符号列表
    parent_stack = Stack()  # 存储父节点的栈
    parse_tree = BinaryTree()  # 解析树
    node = parse_tree  # 当前节点

    for char in exp_list:
        if char == '(':
            # 创建并切换到左子节点
            parent_stack.push(node)
            node.insert_left()
            node = node.left_child
        elif char in '+-*/':
            # 切换回父节点,设置父节点的值
            node = parent_stack.pop()
            node.data = char
            # 创建并切换到右子节点
            parent_stack.push(node)
            node.insert_right()
            node = node.right_child
        elif char in ')':
            # 切换回父节点
            node = parent_stack.pop()
        elif char.isdigit():
            # 设置当前节点的值
            node.data = eval(char)
        else:
            raise ValueError(f'Unknown character: {char}')

    return parse_tree
Ejemplo n.º 17
0
def buildParseTree(fpexp):
    fplist = mystr = re.findall(r'\s*([()+*/-]|\d+)', fpexp)
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()

        elif i == ')':
            currentTree = pStack.pop()

        elif i not in ['+', '-', '*', '/', ')']:
            try:
                currentTree.setRootVal(int(i))
                parent = pStack.pop()
                currentTree = parent

            except ValueError:
                raise ValueError("token '{}' is not a valid integer".format(i))

    return eTree
Ejemplo n.º 18
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)    # 合成后缀表达式
Ejemplo n.º 19
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)
Ejemplo n.º 20
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()
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
Ejemplo n.º 22
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
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
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)
Ejemplo n.º 25
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)  #合成后缀表达式字符串
Ejemplo n.º 26
0
def infix2postfix(infix):
    prec = {
        '(': 1,
        '+': 2,
        '-': 2,
        '*': 3,
        '/': 3,
    }

    stack = Stack()
    infix_list, postfix_list = infix.split(), []

    for char in infix_list:
        if char in string.ascii_uppercase:
            postfix_list.append(char)
        elif char == '(':
            stack.push(char)
        elif char == ')':
            token = stack.pop()
            while token != '(':
                postfix_list.append(token)
                token = stack.pop()
        else:
            while not stack.is_empty() and prec[stack.peek()] >= prec[char]:
                postfix_list.append(stack.pop())
            stack.push(char)

    while not stack.is_empty():
        postfix_list.append(stack.pop())

    return ' '.join(postfix_list)
 def creatS(self,fpexp):
     fplist = fpexp.split()
     p_stack = Stack()
     e_tree = BinaryTree('')
     p_stack.push(e_tree)
     current_tree = e_tree
     for i in fplist:
         if i == "(":
             current_tree.insert_left('')
             p_stack.push(current_tree)
             current_tree = current_tree.get_left_child()
         elif i in "'and','or'":
             current_tree.set_root_val(i)
             current_tree.insert_right('')
             p_stack.push(current_tree)
             current_tree=current_tree.get_right_child()
         elif i in "'not'":
             current_tree = p_stack.pop()
             current_tree.set_root_val(i)
             current_tree.insert_left(False)
             current_tree.insert_right('')
             p_stack.push(current_tree)
             current_tree=current_tree.get_right_child()
         elif i == ')':
             current_tree = p_stack.pop()
         else:
             current_tree.set_root_val(i)
             parent = p_stack.pop()
             current_tree = parent
             if i not in self.symbols:
                 self.symbols.append(i)
     self.val=e_tree
Ejemplo n.º 28
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 buildParseTree(fpexp):
    fplist = split_expression(fpexp)  # Exercise question
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()

        elif i == ')':
            currentTree = pStack.pop()

        elif i not in ['+', '-', '*', '/', ')']:
            try:
                currentTree.setRootVal(int(i))
                parent = pStack.pop()
                currentTree = parent

            except ValueError:
                raise ValueError("token '{}' is not a valid integer".format(i))

    return eTree
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)