0

Suppose I have a tree where internal nodes are operations on floating-point values and leaf nodes are floating-point terminals. Now, I want to traverse this tree and get the resulting function. One way might be to do this:

def Execute(tree):
    result = 0
    symbol = tree.data
    if (symbol in {'/', '*', '+', '-'}):
        if (symbol == '/'):
            result = Execute(tree.left) / Execute(tree.right)
        elif (symbol == '*'):
            result = Execute(tree.left) * Execute(tree.right)
        elif (symbol == '+'):
            result = Execute(tree.left) + Execute(tree.right)
        elif (symbol == '-'):
            result = Execute(tree.left) - Execute(tree.right)
    else:
        return tree.data
    return result

The problem with this is that it would require a lot of calls to a function in Python every time Specifically, is there a way I could convert this tree to a list of Python statements that could be run in a function?

Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • Possible duplicate of [Strategies for simplifying math expressions](http://stackoverflow.com/questions/7540227/strategies-for-simplifying-math-expressions) – gustavodidomenico Nov 16 '15 at 12:52
  • I can see why you'd think that, but I can't wrap my head around the provided answer to that problem. I was hoping for some clarification – Woody1193 Nov 16 '15 at 16:10
  • @gustavodidomenico Not a duplicate. I'm not asking to develop a simplified expression in Python. What I want is just a function that I can construct as I build the tree that I can execute instead of running through the tree. I do NOT want to build all those classes to do this – Woody1193 Nov 19 '15 at 20:06

0 Answers0