import ptoken import parser debug = False def calculate_results(node): if type(node) is parser.Num: return float(node.value) left = calculate_results(node.left) right = calculate_results(node.right) return operate(left, right, node.op) def operate(n1, n2, tokenType): # Utility function to handle dealing with the various mathmatical operations that the engine can process. # Returns the result of any one of five mathmatical operations, else throws an error for unrecognized operations. n1 = float(n1) n2 = float(n2) if tokenType == ptoken.TokenType.add: if debug: print("Adding %f and %f to get %f." %(n1, n2, n1 + n2)) return n1 + n2 elif tokenType == ptoken.TokenType.subtract: if debug: print("Subtracting %f and %f to get %f." %(n1, n2, n1 - n2)) return n1 - n2 elif tokenType == ptoken.TokenType.multiply: if debug: print("Multiplying %f and %f to get %f" %(n1, n2, n1 * n2)) return n1 * n2 elif tokenType == ptoken.TokenType.divide: if debug: print("Dividing %f and %f to get %f" %(n1, n2, n1 / n2)) return n1 / n2 elif tokenType == ptoken.TokenType.power: if debug: print("Raising %f to the power of %f to get %f" %(n1, n2, n1**n2)) return n1 ** n2 else: raise TypeError("Invalid operator value " + str(tokenType) + ".", tokenType)