4

I´m having some trouble using python´s list function for polynomials.

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

I want to adjust this so that:

  • Terms with coefficient 1 are written without the coefficients, e.g. "1x^3" should be written as "x^3".

  • Terms with coefficient 0 should not be written at all, e.g. "x^4 + x^3 + 0*x^2 + 0*x + 0" should be simplified as "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
Yang MingHui
  • 380
  • 4
  • 14
Alexander West
  • 81
  • 1
  • 1
  • 9

6 Answers6

4

Here's an alternative way that also deals with 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
coder
  • 12,832
  • 5
  • 39
  • 53
3

Here is a one liner to convert a list to a polynomial with the correct conditions for coefficients

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'

To print in opposite order (high powers first):

    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)
Gerges
  • 6,269
  • 2
  • 22
  • 44
1

You can do this way as well,

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'
Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27
1

I used enumerate to do the degree trick and avoided stuff you don't need with simple flow instructions. Hope it is not that cryptic 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])
dmitry_romanov
  • 5,146
  • 1
  • 33
  • 36
1

Minimal changes to your code that works as desired, though I suggest you to understand the first answer by 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
Emmet B
  • 5,341
  • 6
  • 34
  • 47
0

This might help(not exactly a one-liner):

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-presentable form of the function 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 output:

 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
tkhurana96
  • 919
  • 7
  • 25