(expr, fct)
return result
If a sympy 'Expr' is of the form:

    expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n + expr_11*a_1*a_1
           + ... + expr_ij*a_i*a_j + ... + expr_nn*a_n*a_n

    where all the a_j are noncommuting symbols in basis then

    bilinear_function(expr) = bilinear_product(expr_0) + bilinear_product(expr_1*a_1) + ... + bilinear_product(expr_n*a_n)
                              + bilinear + product(expr_11*a_1*a_1) + ... + bilinear_product(expr_nn*a_n*a_n)
If a sympy 'Expr' is of the form:
If a sympy Expr is of the form :
def bilinear_function(expr, fct):
    """
    If a sympy 'Expr' is of the form:

    expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n + expr_11*a_1*a_1
           + ... + expr_ij*a_i*a_j + ... + expr_nn*a_n*a_n

    where all the a_j are noncommuting symbols in basis then

    bilinear_function(expr) = bilinear_product(expr_0) + bilinear_product(expr_1*a_1) + ... + bilinear_product(expr_n*a_n)
                              + bilinear + product(expr_11*a_1*a_1) + ... + bilinear_product(expr_nn*a_n*a_n)
    """
    if expr.is_commutative:
        return expr
    expr = expand(expr)
    if isinstance(expr, (Mul, Pow, Symbol)):  # only one additive term
        return bilinear_product(expr, fct)
    elif isinstance(expr, Add):  # multiple additive terms
        result = S.Zero
        for arg in expr.args:
            result += bilinear_product(arg, fct)
    return result
def bilinear_function ( expr , fct ) : if expr . is_commutative : return expr expr = expand ( expr ) if isinstance ( expr , ( Mul , Pow , Symbol ) ) : # only one additive term return bilinear_product ( expr , fct ) elif isinstance ( expr , Add ) : # multiple additive terms result = S . Zero for arg in expr . args : result += bilinear_product ( arg , fct ) return result