nd2py.core.tree package#
Submodules#
nd2py.core.tree.iter_postorder module#
nd2py.core.tree.iter_preorder module#
nd2py.core.tree.match module#
nd2py.core.tree.tree_mixin module#
- class nd2py.core.tree.tree_mixin.TreeMixin[source]#
Bases:
objectMixin 类:负责维护 Symbol 作为一棵符号树的结构关系 (parent, operands) 并提供树形操作方法。 宿主类必须提供以下属性:
self.n_operands
self.parent
self.operands
- n_operands: int#
- parent: 'Symbol' | None#
- operands: List['Symbol']#
- property root#
- iter_preorder()[source]#
Non-recursive preorder traversal of the Symbol tree using an explicit stack.
- replace(child: Symbol, other: Symbol, no_warn=False)[source]#
Replace current expression (or subexpression denoted by child) with another expression.
- match(pattern: Symbol) Dict[str, Symbol] | None[source]#
Match a pattern expression against self expression.
This function checks if the pattern can match the self expression by comparing their tree structures. Variables in the pattern can match any subexpression. The same variable name must match the same subexpression throughout the pattern.
- Parameters:
pattern – The pattern expression containing variables to be matched.
- Returns:
A dictionary mapping variable names from the pattern to their matched subexpressions, or None if the pattern does not match.
Examples
>>> from nd2py import Variable, sin, Add, Mul >>> from nd2py.core.tree import match >>> a = Variable('a') >>> x = Variable('x')
>>> # sin(a) matches sin(x*2+1) >>> f = sin(x*2+1) >>> f.match(sin(a)) {'a': x + 2*x}
>>> # a+a matches sin(x)+sin(x) (same variable must match same subexpression) >>> f = sin(x) + sin(x) >>> f.match(a+a) {'a': sin(x)}
>>> # a+a does NOT match sin(x)+cos(x) (different subexpressions) >>> f = sin(x) + cos(x) >>> f.match(a+a) None
>>> # a+b matches both sin(x)+sin(x) and sin(x)+cos(x) >>> f = sin(x) + sin(x) >>> f.match(a+b) {'a': sin(x), 'b': sin(x)}