本文介绍了python中的漂亮多项式打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用哪种格式的字符串来打印类似的表达式

What format string would I use to print expressions like

2x^3 + 3x^2 - 6x + 1(注意标志两侧的空格)

2x^3 + 3x^2 - 6x + 1 (notice spaces on either side of signs)

30.1x^2 + 60.2x - 90.3

和(如果简单的话)

x^2 + 2x + 1(如果系数为1,则x上的项均无系数).

x^2 + 2x + 1 (no coefficient on terms in x if coefficient is 1).

我尝试过在这样的强制符号之间插入填充:

I've tried inserting padding between a forced sign like this:

"{0: =+}x^2 {1: =+}x {2: =+}".format(1, -2, 3)

,但不显示填充.

推荐答案

假设您有表示"2x^3 + 3x^2 - 6x + 1"[1, -6, 3, 2]:

class Polynomial(list):
    def __repr__(self):
        # joiner[first, negative] = str
        joiner = {
            (True, True): '-',
            (True, False): '',
            (False, True): ' - ',
            (False, False): ' + '
        }

        result = []
        for power, coeff in reversed(list(enumerate(self))):
            j = joiner[not result, coeff < 0]
            coeff = abs(coeff)
            if coeff == 1 and power != 0:
                coeff = ''

            f = {0: '{}{}', 1: '{}{}x'}.get(power, '{}{}x^{}')

            result.append(f.format(j, coeff, power))

        return ''.join(result) or '0'
>>> Polynomial([1, -6, 3, 2])
2x^3 + 3x^2 - 6x + 1
>>> Polynomial([1, -6, 3, -2])
-2x^3 + 3x^2 - 6x + 1
>>> Polynomial([])
0

这篇关于python中的漂亮多项式打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:40