code: def replace(self, expression: Expression, max_count: int=math.inf) -> Union[Expression, Sequence[Expression]]:
          
          replaced = True
          replace_count = 0
          while replaced and replace_count < max_count:
              replaced = False
              for subexpr, pos in preorder_iter_with_position(expression):
                  try:
                      replacement, subst = next(iter(self.matcher.match(subexpr)))
                      result = replacement(**subst)
                      expression = functions.replace(expression, pos, result)
                      replaced = True
                      break
                  except StopIteration:
                      pass
              replace_count += 1
          return expression
docs: Replace all occurrences of the patterns according to the replacement rules.
  
          Args:
              expression:
                  The expression to which the replacement rules are applied.
              max_count:
                  If given, at most *max_count* applications of the rules are performed. Otherwise, the rules
                  are applied until there is no more match. If the set of replacement rules is not confluent,
                  the replacement might not terminate without a *max_count* set.
  
          Returns:
              The resulting expression after the application of the replacement rules. This can also be a sequence of
              expressions, if the root expression is replaced with a sequence of expressions by a rule.