Printing a polynomial in python

前端 未结 4 1521
悲&欢浪女
悲&欢浪女 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:41

    Python has really powerful iteration that will help you out here.

    For starters, don't pass the len of something to range. Iterate over the something directly.

    for x in self.coeffs:
    

    This won't completely help you, though, since the index of the iteration is needed for the power. enumerate can be used for that.

    for i, x in enumerate(self.coeffs):
    

    This presents another problem, however. The powers are backwards. For this, you want reversed.

    for i, x in enumerate(reversed(self.coeffs)):
    

    From here you just need to handle your output:

    items = []
    for i, x in enumerate(reversed(self.coeffs)):
        if not x:
            continue
        items.append('{}x^{}'.format(x if x != 1 else '', i))
    result = ' + '.join(items)
    result = result.replace('x^0', '')
    result = result.replace('^1 ', ' ')
    result = result.replace('+ -', '- ')
    

提交回复
热议问题