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

    expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n

    where all the a_j are noncommuting symbols in basis then

    f(expr) = fct(expr_0) + fct(expr_1)*a_1 + ... + fct(expr_n)*a_n

    is returned
If a sympy 'Expr' is of the form:
If a sympy Expr is of the form :
def coef_function(expr, fct):
    """
    If a sympy 'Expr' is of the form:

    expr = expr_0 + expr_1*a_1 + ... + expr_n*a_n

    where all the a_j are noncommuting symbols in basis then

    f(expr) = fct(expr_0) + fct(expr_1)*a_1 + ... + fct(expr_n)*a_n

    is returned
    """
    expr = expand(expr)
    if isinstance(expr, Mul):
        (coefs, bases) = expr.args_cnc()
        return fct(Mul(*coefs)) * bases[0]
    elif isinstance(expr, Symbol):
        if expr.is_commutative:
            return fct(expr)
        else:
            return expr
    elif isinstance(expr, Add):
        result = S.Zero
        for arg in expr.args:
            term = arg.args_cnc()
            if term[1] == []:
                result += fct(Mul(*term[0]))
            else:
                result += fct(Mul(*term[0])) * fct(term[1][0])
    return result
def coef_function ( expr , fct ) : expr = expand ( expr ) if isinstance ( expr , Mul ) : ( coefs , bases ) = expr . args_cnc ( ) return fct ( Mul ( * coefs ) ) * bases [ 0 ] elif isinstance ( expr , Symbol ) : if expr . is_commutative : return fct ( expr ) else : return expr elif isinstance ( expr , Add ) : result = S . Zero for arg in expr . args : term = arg . args_cnc ( ) if term [ 1 ] == [ ] : result += fct ( Mul ( * term [ 0 ] ) ) else : result += fct ( Mul ( * term [ 0 ] ) ) * fct ( term [ 1 ] [ 0 ] ) return result