Removing and replacing polynomial coefficients in Python

I'm having trouble using the python list function for polynomials.

For example, if I write poynomial p1 = [0, 0, 0, 1, 1], I get the output1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0

I want to configure this so that:

  • Conditions with a coefficient of 1 are recorded without coefficients, for example. "1x^3"should be written as "x^3".

  • Conditions with a coefficient of 0 should not be written at all, for example. "x^4 + x^3 + 0*x^2 + 0*x + 0"should be simplified how "x^4 + x^3".

Is there a command for this in python?

Thanks in advance.

/ Alex

//the code

def polynomial_to_string(p_list):
    terms = []
    degree = 0

    for coeff in p_list:
        if degree == 0:
            terms.append(str(coeff))
        elif degree == 1:
            terms.append(str(coeff) + 'x')
        else:
            term = str(coeff) + 'x^' + str(degree)
            terms.append(term)
        degree += 1

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string
+4
source share
6 answers

Here's an alternative way that also applies to the sign:

>>> def getsign(n):
...     return '-' if n<0 else '+'
...
>>>
>>> def polynom(l):
...     pl = ['' if j==0 else '{}x^{}'.format(getsign(j),i) if j==1 or j==-1 else '{}{}x^{}'.format(getsign(j),abs(j),i) for i,j in enumerate(l)]
...     return ''.join([str(l[0])]+pl) if l[0]!=0  else ''.join(pl)
...
>>> print polynom([0, 0, 0, -1, -2, 1, 7])
-x^3-2x^4+x^5+7x^6
+4
source

p = [0, 0, 0, 1, 1]

s = ' + '.join('%d*x^%d' % (pi, i) if pi != 1 else 'x^%d' % i for i, pi in enumerate(p) if pi != 0)

s

'x^3 + x^4'

( ):

    s = ' + '.join('%d*x^%d' % (pi, i) if pi != 1 else 'x^%d' % i for i, pi in reversed(list(enumerate(p))) if pi != 0)
+3

,

def unity(num):
    if num==1:return('')
    elif num=='':return('.1')
    return num

coeffs = [3,2,0,1,6] #6x^4 + 1x^3 + 0x^2 + 2x + 1
variables = ['x^4','x^3','x^2','x','']

output = ' + '.join([str(unity(i))+unity(j) for i,j in zip(coeffs[::-1],variables) if i])
print(output)
>>>'6x^4 + x^3 + 2x + 3.1'
+1

I used enumerateto do the trick degreeand avoid unnecessary things that you do not need with simple flow instructions. Hope this is not as mysterious as other solutions; -)

def polynomial_to_string(p_list):
    terms = []

    for degree, coeff in enumerate(p_list):
        if not coeff:
            continue
        if coeff in [1, '1']:
            coeff = ''
        if degree == 0:
            terms.append(str(coeff))
        elif degree == 1:
            terms.append(str(coeff) + 'x')
        else:
            term = str(coeff) + 'x^' + str(degree)
            terms.append(term)

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string


print polynomial_to_string([0, 0, 0, 1, 1])
+1
source

Minimal changes to your code, which works as desired , although I suggest you understand the first answer from Gerges Dib.

def polynomial_to_string(p_list):
    terms = []
    degree = 0

    for coeff in p_list:
        if coeff > 0:
            if coeff == 1:
                coeff = ''
            if degree == 0:
                terms.append(str(coeff))
            elif degree == 1:
                terms.append(str(coeff) + 'x')
            else:
                term = str(coeff) + 'x^' + str(degree)
                terms.append(term)
        degree += 1

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string
+1
source

This may help (not exactly one line):

def polynonmial_equation(coefficients):
        degree = len(coefficients) - 1

        temp = "".join(map(lambda x: "" if x[1] == 0 else [" - ", " + "][x[1]> 0] + [str(abs(x[1])) + "*", ""][abs(x[1]) == 1] + "x^" + str(degree -x[0]), enumerate(reversed(coefficients)))).strip()

        return temp if temp.startswith('-') else temp[1:]

More re-presentation of the form above:

def polynonmial_equation(coefficients):
    degree = len(coefficients) - 1
    temp = "".join(map(lambda x: "" if x[1] == 0 else
                   [" - ", " + "][x[1] > 0] +
                   [str(abs(x[1])) + "*", ""][abs(x[1]) == 1] +
                   "x^" + str(degree - x[0]),
                   enumerate(reversed(coefficients)))).strip()
    return temp if temp.startswith('-') else temp[1:]


print(polynonmial_equation([0, 0, 0, 1, 1]))
print(polynonmial_equation([0, 0, 0, 1, -1]))
print(polynonmial_equation([0, 0, 0, -1, -1]))
print(polynonmial_equation([0, 0, 0, -1, 1]))
print()
print(polynonmial_equation([0, 0, 0, 1, 3]))
print(polynonmial_equation([0, 0, 0, 1, -3]))
print(polynonmial_equation([0, 0, 0, -1, -3]))
print(polynonmial_equation([0, 0, 0, -1, 3]))
print()
print(polynonmial_equation([1, 2, 3, 4, 5]))
print(polynonmial_equation([-1, 2, -3, 4, -5]))
print(polynonmial_equation([-1, 2, 0, 4, -5]))
print(polynonmial_equation([0, 0, 6, -1, -3]))
print(polynonmial_equation([0, -3, 4, -1, 0]))

And the conclusion:

 x^4 + x^3
- x^4 + x^3
- x^4 - x^3
 x^4 - x^3

 3*x^4 + x^3
- 3*x^4 + x^3
- 3*x^4 - x^3
 3*x^4 - x^3

 5*x^4 + 4*x^3 + 3*x^2 + 2*x^1 + x^0
- 5*x^4 + 4*x^3 - 3*x^2 + 2*x^1 - x^0
- 5*x^4 + 4*x^3 + 2*x^1 - x^0
- 3*x^4 - x^3 + 6*x^2
- x^3 + 4*x^2 - 3*x^1
0
source

Source: https://habr.com/ru/post/1692830/


All Articles