def apply_to(self, expression: Expression) -> List[Expression]: from_side = self.left to_side = self.right # Get the subtrees of the expression that have the same root as from side. # by level means that we also get the level of that subtree to know if the # subtree could match from_side subtrees = expression.get_subtrees_with_root_func_by_level(from_side) from_side_depth = from_side.get_depth() expression_depth = expression.get_depth() results = [] for subtree in subtrees: sub_expression = subtree['expression'] level = subtree['level'] # Example Derivative(x) have depth 2 and Derivative(f(x)+g(x)) have depth 3 # So, if the depth of the subtree is less than the from_side of the theorem # it can't be applied if level <= expression_depth - from_side_depth: application_possibilities = self._apply_to(sub_expression, from_side, to_side) for possibility in application_possibilities: if sub_expression != expression: # Example: # expression cos(x) + Derivative(2*x) # sub_expression = Derivative(2*x) # possibility = 2 * Derivative(x) # replace sub_expression with possibility # result = cos(x) + 2 * Derivative(x) result = expression.get_copy() result.replace(sub_expression, possibility) else: result = possibility results += [result] return results
def test_get_depth_with_user_defined_func(self): expression = Expression("Derivative(f(x) + g(x), x)", is_latex=False) self.assertEquals(3, expression.get_depth())