Exemplo n.º 1
0
def collect_square(f, term, square):
    '''collect_square(x**5+x**2, x, XX) == x*XX**2+XX'''

    g = collect(f, term)
    h = Poly(g, term)
    s = zero
    for (e, ), coeff in h.all_terms():
        t = square**(e // 2)
        if e % 2:
            t *= term
        s += coeff * t
    return s
Exemplo n.º 2
0
def separate_odd_pow_terms(f, term):
    '''separate_odd_pow_terms(x**3+x**2+x+1, x) = (x**2+1, x**3+x)'''

    g = collect(f, term)
    h = Poly(g, term)
    odd = even = zero
    for (e, ), coeff in h.all_terms():
        t = term**e * coeff
        if e % 2:
            odd += t
        else:
            even += t
    return even, odd
Exemplo n.º 3
0
def poly_descent(expr):
    if expr[0] == '-' and expr[1:].isdigit() or expr.isdigit():
        return expr
    p = Poly(parse_expr(str(expr)))
    vars = set([])
    for c in str(expr):
        if c.isalpha():
            vars.add(c)
    assert len(vars) > 0
    if len(vars) > 1:
        return expr
    var = vars.pop()
    s = ''
    lst = sorted(p.all_terms(), key=lambda x: x[0], reverse=True)
    for d, c in lst:
        d = d[0]
        if d == 0:
            if c > 0:
                s += f' + {c}'
            elif c < 0:
                s += f' - {abs(c)}'
        elif d == 1:
            if c > 0 and c != 1:
                s += f' + {c}*{var}'
            elif c == 1:
                s += f' + {var}'
            elif c < 0 and c != -1:
                s += f' - {abs(c)}*{var}'
            elif c == -1:
                s += f' - {var}'

        else:
            if c > 0 and c != 1:
                s += f' + {c}*{var}**{d}'
            elif c == 1:
                s += f' + {var}**{d}'
            elif c < 0 and c != -1:
                s += f' - {abs(c)}*{var}**{d}'
            elif c == -1:
                s += f' - {var}**{d}'
    if s[:3] == ' - ':
        s = '-' + s[3:]
    if s[:3] == ' + ':
        s = s[3:]

    return s