Printing a polynomial in python

前端 未结 4 1556
悲&欢浪女
悲&欢浪女 2021-01-16 18:16

I\'m making a Polynomial python class and as part of that, I need to print a polynomial nicely. The class is given a list that represents the coefficients of the polynomial

4条回答
  •  余生分开走
    2021-01-16 18:48

    This should print: 2*x^2 + 3*x + 4*1 for p1

    class Polynomial:
    
    def __init__(self, coefficients):
        self.coeffs=coefficients
    
    def __str__(self):
        out = ''
        size = len(self.coeffs)    
        for i in range(size):      #To Solve the ignored coefficient
            if self.coeffs[i] != 0:
                out += ' + %g*x^%d' % (self.coeffs[i],size-i-1)   #To solve Backwards order
        # Fixing
        out = out.replace('+ -', '- ')
        out = out.replace('x^0', '1')
        out = out.replace(' 1*', ' ')
        out = out.replace('x^1 ', 'x ')
        if out[0:3] == ' + ':  # remove initial +
            out = out[3:]
        if out[0:3] == ' - ':  # fix spaces for initial -
            out = '-' + out[3:]
        return out
    
    
    
    
    a = Polynomial([2,3,4])
    
    
    print(a)
    

提交回复
热议问题