Printing a polynomial in python

前端 未结 4 1522
悲&欢浪女
悲&欢浪女 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条回答
  •  梦毁少年i
    2021-01-16 18:31

    Here's very simple approach of iterating over coeffs, building string chunk by chunk and joining it afterwards.

    class Polynomial:
        def __init__(self, coefficients):
            self.coeffs = coefficients
    
        def __str__(self):
            chunks = []
            for coeff, power in zip(self.coeffs, range(len(self.coeffs) - 1, -1, -1)):
                if coeff == 0:
                    continue
                chunks.append(self.format_coeff(coeff))
                chunks.append(self.format_power(power))
            chunks[0] = chunks[0].lstrip("+")
            return ''.join(chunks)
    
        @staticmethod
        def format_coeff(coeff):
            return str(coeff) if coeff < 0 else "+{0}".format(coeff)
    
        @staticmethod
        def format_power(power):
            return 'x^{0}'.format(power) if power != 0 else ''
    
    
    assert str(Polynomial([2, -3, 0, 5])) == "2x^3-3x^2+5"
    

提交回复
热议问题