Exemplo n.º 1
0
def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)

    for i in fplist:
        if i == '(':
            # 如果当前符号是“(”,添加一个新节点作为当前节点的左子节点,并且下降到左子节点
            eTree.insertLeft('')
            pStack.push(eTree)
            eTree = eTree.getLeftChild()
        elif i not in ['+', '-', '/', '*', ')']:
            # 如果当前符号是数字,将当前节点的根值设置为该数字并返回父节点
            eTree.setRootVal(int(i))
            parent = pStack.pop()
            eTree = parent
        elif i in ['+', '-', '/', '*']:
            eTree.setRootVal(i)
            eTree.insertRight('')
            pStack.push(eTree)
            eTree = eTree.getRightChild()
        elif i == ')':
            eTree = pStack.pop()
        else:
            raise ValueError

    return eTree
Exemplo n.º 2
0
def build_parse_tree(fpexp):
    fplist = fpexp.split()
    for i in fplist:
        if i.__contains__('(') and i != '(':
            index = fplist.index(i)
            i_l = i.split('(')
            fplist[index] = i_l[-1]
            for j in range(len(i_l)-1):
                fplist.insert(index, '(')
        if i.__contains__(')') and i != ')':
            index = fplist.index(i)
            i_l = i.split(')')
            fplist[index] = i.split(')')[0]
            for j in range(len(i_l)-1):
                fplist.insert(index+1, ')')
    pstack = Stack()
    current_tree = BinaryTree('')
    current_tree.insertLeft('')
    pstack.push(current_tree)
    current_tree = current_tree.getLeftChild()
    for i in fplist:
        if i == '(':
            current_tree.insertLeft('')
            pstack.push(current_tree)
            current_tree = current_tree.getLeftChild()
        elif i not in ['and', 'or', ')']:
            current_tree.setRootVal(i)
            parent = pstack.pop()
            current_tree = parent

        elif i in ['and', 'or']:
            if current_tree.getRootVal() != "":
                pstack.push(current_tree)
                current_tree = BinaryTree('')
                current_tree.leftChild = pstack.pop()
            current_tree.setRootVal(i)
            current_tree.insertRight('')
            pstack.push(current_tree)
            current_tree = current_tree.getRightChild()
        elif i == ')':
            current_tree = pstack.pop()
        else:
            raise ValueError
    return current_tree
Exemplo n.º 3
0
def print_exp(tree: BinaryTree):
    # 优化后的方法,去掉每个数字的左右括号
    sVal = ''

    if tree:
        str_val = str(tree.getRootVal())
        result = print_exp(tree.getLeftChild()) + str_val + print_exp(
            tree.getRightChild())

        if str_val.isnumeric():
            sVal = result
        else:
            sVal = '(' + result + ')'

    return sVal
Exemplo n.º 4
0
def postorder_evaluate(tree: BinaryTree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }

    if tree:
        res1 = postorder_evaluate(tree.getLeftChild())
        res2 = postorder_evaluate(tree.getRightChild())
        if res1 and res2:
            return opers[tree.getRootVal()](res1, res2)
        else:
            return tree.getRootVal()
Exemplo n.º 5
0
def evaluate(parseTree: BinaryTree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }

    leftC = parseTree.getLeftChild()
    rightC = parseTree.getRightChild()

    if leftC and rightC:
        fn = opers[parseTree.getRootVal()]
        return fn(evaluate(leftC), evaluate(rightC))
    else:
        return parseTree.getRootVal()
Exemplo n.º 6
0
def buildParseTree(expr):
    expr = expr.split()
    binaryTree = BinaryTree('')
    stack = Stack()
    stack.push(binaryTree)  # 避免空栈弹出时报错
    currentTree = binaryTree
    for i in expr:
        if i == '(':
            currentTree.insertLeft('')
            stack.push(currentTree)
            currentTree = binaryTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))  # 非数字int()就会报错
            currentTree = stack.pop()
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            stack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = stack.pop()
        else:
            raise ValueError
    return binaryTree
Exemplo n.º 7
0
def preorder(tree: BinaryTree):
    # 前序遍历
    if tree:
        print(tree.getRootVal())
        preorder(tree.getLeftChild())
        preorder(tree.getRightChild())
Exemplo n.º 8
0
def postorder(tree: BinaryTree):
    # 后序遍历
    if tree:
        postorder(tree.getLeftChild())
        postorder(tree.getRightChild())
        print(tree.getRootVal())
Exemplo n.º 9
0
def inorder(tree: BinaryTree):
    # 中序遍历
    if tree:
        inorder(tree.getLeftChild())
        print(tree.getRootVal())
        inorder(tree.getRightChild())
Exemplo n.º 10
0
class RuleParser(object):
    tree = None
    operators = {'and': operator.and_, 'or': operator.or_}

    def __init__(self, rule, globals=globals()):
        tokens = rule.split()
        pStack = Stack()
        self.tree = BinaryTree('')
        pStack.push(self.tree)
        current_tree = self.tree
        is_func_args = False
        self.globals = globals
        for token in tokens:
            # Open bracket.
            if token == '(':
                if is_func_args:
                    parent = pStack.pop()
                    current_tree = parent
                current_tree.insertLeft('')
                pStack.push(current_tree)
                current_tree = current_tree.getLeftChild()
                is_func_args = False
            # Function name or arguments.
            elif token.lower() not in ['and', 'or', ')']:
                if not is_func_args:
                    current_tree.setRootVal((token, []))
                    is_func_args = True
                    continue
                current_tree.key[1].append(token)
            elif token.lower() in ['and', 'or']:
                if is_func_args:
                    parent = pStack.pop()
                    current_tree = parent
                current_tree.setRootVal(token)
                current_tree.insertRight('')
                pStack.push(current_tree)
                current_tree = current_tree.getRightChild()
                is_func_args = False
            elif token == ')':
                if is_func_args:
                    parent = pStack.pop()
                    current_tree = parent
                current_tree = pStack.pop()
                is_func_args = False
            else:
                raise ValueError
        self.tree = current_tree
        # If we have only 1 node (Example: "func1 arg1"), then
        # the root node is empty. Make it left child which is not empty.
        if self.tree.getRightChild() is None and self.tree.getLeftChild(
        ) is not None:
            self.tree = self.tree.getLeftChild()

    def eval_rule(self):
        return self.eval_rule_(self.tree)

    def eval_rule_(self, tree):
        left_child = None
        right_child = None
        if tree:
            left_child = self.eval_rule_(tree.getLeftChild())
            right_child = self.eval_rule_(tree.getRightChild())
            if left_child is not None and right_child is not None:
                return self.operators[tree.getRootVal().lower()](left_child,
                                                                 right_child)
            else:
                root_value = tree.getRootVal()
                return self.globals[root_value[0]](" ".join(
                    root_value[1])) if type(
                        root_value) is not bool else root_value

    def serialize(self):
        return self.serialize_(self.tree)

    def serialize_(self, tree):
        value = ""
        if tree:
            if tree.getLeftChild():
                value = self.serialize_(tree.getLeftChild())
            current_node_value = "{} {}".format(tree.key[0], " ".join(
                tree.key[1])) if type(tree.key) is tuple else " {}".format(
                    tree.key)
            value += current_node_value
            if tree.getLeftChild():
                value = "{} {}".format(value,
                                       self.serialize_(tree.getRightChild()))
            if tree.getLeftChild() and tree.getLeftChild():
                value = "( {} )".format(value)
        return value
from pythonds.trees.binaryTree import BinaryTree
import operator

x = BinaryTree('*')
x.insertLeft('+')
l = x.getLeftChild()
l.insertLeft(4)
l.insertRight(5)
x.insertRight(7)


def printexp(tree):
  sVal = ""
  if tree:
      sVal = '(' + printexp(tree.getLeftChild())
      sVal = sVal + str(tree.getRootVal())
      sVal = sVal + printexp(tree.getRightChild())+')'
  return sVal

def postordereval(tree):
  opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
  res1 = None
  res2 = None
  if tree:
      res1 = postordereval(tree.getLeftChild())
      res2 = postordereval(tree.getRightChild())
      if res1 and res2:
          return opers[tree.getRootVal()](res1,res2)
      else:
          return tree.getRootVal()
Exemplo n.º 12
0
# binary tree or not
from pythonds.trees.binaryTree import BinaryTree
prev=None
def isBinarySearchTree(root):
    global prev
    if root:
        if not isBinarySearchTree(root.leftChild):
            return False
        if (prev and prev.key>root.key):
            return False
        prev=root
        if not isBinarySearchTree(root.rightChild):
            return False
    return True

tree=BinaryTree(4)
tree.insertLeft(2)
tree.insertRight(5)
ls=tree.getLeftChild()
ls.insertLeft(1)
ls.insertRight(3)
print isBinarySearchTree(tree)


Exemplo n.º 13
0
            if treeNode.getRightChild():
                leftNode = treeNode.getLeftChild()
                rightNode = treeNode.getRightChild()
                return BinaryExpression(treeNode.key,
                                        ExpressionFactory.getExp(leftNode),
                                        ExpressionFactory.getExp(rightNode))
            elif treeNode.getLeftChild():
                leftNode = treeNode.getLeftChild()
                return UnaryExpression(treeNode.key,
                                       ExpressionFactory.getExp(leftNode))
            else:
                return ConstExpression(treeNode.key)


if __name__ == "__main__":
    #strExp="-12*(3+5)+6"
    rootNode = Tree("+")
    rootNode.insertRight(6)
    rootNode.insertLeft("*")
    treeNode = rootNode.getLeftChild()
    treeNode.insertLeft("-")
    tmpNode = treeNode.getLeftChild()
    tmpNode.insertLeft(12)
    treeNode.insertRight("+")
    tmpNode = treeNode.getRightChild()
    tmpNode.insertLeft(3)
    tmpNode.insertRight(5)

    exp = ExpressionFactory.getExp(rootNode)
    print exp.interpret()
Exemplo n.º 14
0
# binary tree or not
from pythonds.trees.binaryTree import BinaryTree
prev = None


def isBinarySearchTree(root):
    global prev
    if root:
        if not isBinarySearchTree(root.leftChild):
            return False
        if (prev and prev.key > root.key):
            return False
        prev = root
        if not isBinarySearchTree(root.rightChild):
            return False
    return True


tree = BinaryTree(4)
tree.insertLeft(2)
tree.insertRight(5)
ls = tree.getLeftChild()
ls.insertLeft(1)
ls.insertRight(3)
print isBinarySearchTree(tree)
Exemplo n.º 15
0
#!/usr/local/python3.5/bin
# -*-  coding:utf-8 -*-

from pythonds.trees.binaryTree import BinaryTree

myTree = BinaryTree('A')
# print(myTree.getRootVal())
myTree.insertLeft('B')
myTree.insertRight('C')
# print(myTree.getLeftChild().getRootVal())
# print(myTree.getRightChild().getRootVal())
myTree.getLeftChild().insertLeft('D')
myTree.getLeftChild().insertRight('E')
# print(myTree.getLeftChild().getLeftChild().getRootVal())
# print(myTree.getLeftChild().getRightChild().getRootVal())
myTree.getRightChild().insertLeft('F')
myTree.getRightChild().insertRight('G')
# print(myTree.getRightChild().getLeftChild().getRootVal())
# print(myTree.getRightChild().getRightChild().getRootVal())
myTree.getLeftChild().getRightChild().insertLeft('H')
myTree.getLeftChild().getRightChild().insertRight('I')
# print(myTree.getLeftChild().getRightChild().getLeftChild().getRootVal())
# print(myTree.getLeftChild().getRightChild().getRightChild().getRootVal())
myTree.getRightChild().getRightChild().insertLeft('J')
myTree.getRightChild().getRightChild().insertRight('K')

# print(myTree.getRightChild().getRightChild().getLeftChild().getRootVal())
# print(myTree.getRightChild().getRightChild().getRightChild().getRootVal())


# 前序遍历
Exemplo n.º 16
0
from pythonds.trees.binaryTree import BinaryTree
import operator

x = BinaryTree('*')
x.insertLeft('+')
l = x.getLeftChild()
l.insertLeft(4)
l.insertRight(5)
x.insertRight(7)


def printexp(tree):
    sVal = ""
    if tree:
        sVal = '(' + printexp(tree.getLeftChild())
        sVal = sVal + str(tree.getRootVal())
        sVal = sVal + printexp(tree.getRightChild()) + ')'
    return sVal


def postordereval(tree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }
    res1 = None
    res2 = None
    if tree:
        res1 = postordereval(tree.getLeftChild())
Exemplo n.º 17
0
def build_tree_expression(elements):
    stack = Stack()
    tree = BinaryTree('')
    if len(elements) == 1:
        tree.setRootVal(elements[0])
        return tree
    stack.push(tree)
    for i in range(len(elements)):
        if (elements[i] == '(') or (i == 0):
            tree.insertLeft('')
            if elements[i] == '(':
                stack.push("(")
            stack.push(tree)
            tree = tree.getLeftChild()
            if elements[i] != '(':
                tree.setRootVal(elements[i])
                parent = stack.pop()
                tree = parent
        elif elements[i] not in ['+', '-', '*', '/', ')']:
            tree.setRootVal(elements[i])
            parent = stack.pop()
            tree = parent
        elif elements[i] in ['+', '-', '*', '/']:
            sign = elements[i]
            if tree.getRootVal() in ['+', '-', '*', '/']:
                if sign in ['+', '-'] or elements[i - 1] == ')':
                    temp = BinaryTree('')
                    parent = stack.pop()
                    if stack.size() == 0:
                        temp.insertLeft(parent)
                        parent = temp
                        tree = parent
                        stack.push(parent)
                    elif parent == "(":
                        temp.insertLeft(tree)
                        parent = stack.pop()
                        parent.insertRight(temp)
                        stack.push(parent)
                        stack.push("(")
                        tree = parent.getRightChild()
                    else:
                        temp.insertLeft(tree)
                        parent.insertRight(temp)
                        stack.push(parent)
                        tree = parent.getRightChild()
                elif sign in ['*', '/']:
                    rChild = tree.getRightChild()
                    rChild.insertLeft(rChild.getRootVal())
                    tree = rChild
            tree.setRootVal(elements[i])
            tree.insertRight('')
            stack.push(tree)
            tree = tree.getRightChild()
        elif elements[i] == ')':
            parent = ""
            while parent != "(":
                parent = stack.pop()
                if parent == "(":
                    tree = stack.pop()
            stack.push(tree)
        if i + 1 == len(elements):
            for j in range(stack.size()):
                parent = stack.pop()
                tree = parent
    return tree
Exemplo n.º 18
0
Arquivo: Tree.py Projeto: uestcwm/-ML-
r = BinaryTree('a')
print(r.getRootVal())  #a
print(r.getLeftChild())  #None
r.insertLeft('b')
print(r.getLeftChild())  #<__main__.BinaryTree object at 0x0000000005FFC780>
print(r.getLeftChild().getRootVal())  #b
r.insertRight('c')
print(r.getRightChild())  #<__main__.BinaryTree object at 0x0000000005DA2898>
print(r.getRightChild().getRootVal())  #c
r.getRightChild().setRootVal('hello')
print(r.getRightChild().getRootVal())

from pythonds.basic.stack import Stack
from pythonds.trees.binaryTree import BinaryTree


def buildParseTree(formula):
    formulalist = formula.split()  #['(','3','+','(','4','*','5',')',')']
    rootStack = Stack()  #用于跟踪父节点
    Tree = BinaryTree('')  #创建一个二叉树
    rootStack.push(Tree)
    currentTree = Tree
    for i in formulalist:
        if i == '(':
            currentTree.insertLeft('')
            rootStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = rootStack.pop()
            cerrentTree = parent