漂亮的打印多项式与字典 python

Pretty printing polynomials with dictionary python

我正在努力用多项式创建 __ str __ 函数(又名漂亮的打印),其中字典用于包含作为键的幂和作为系数的元素。我已经用列表完成了,但我还没有掌握字典。有什么需要改进的吗?

你可以在第二个多项式中看到,如果我的最后一个常数不是常数,用 reverse() 函数排列键后,加号总是在那里,我该怎么做才能防止这种情况发生?顺便说一句,我正在尝试重载运算符,在完成此操作后,我将尝试执行 __ add____ mul____ sub____ call__... 虽然我会先完成这个:P

class Polynomial(object):                                
  def __init__(self, coefficients):
    self.coefficients = coefficients

  def __str__(self):
     polyd = self.coefficients
     exponent = polyd.keys()  
     exponent.reverse()          
     polytostring = ' '
     for i in exponent:
        exponent = i
        coefficient = polyd[i]
        if i == 0:
            polytostring += '%s' % coefficient
            break
        polytostring += '%sx^%s + ' % (coefficient, exponent)


     return polytostring


dict1 = {0:1,1:-1}
p1 = Polynomial(dict1)

dict2 = {1:1,4:-6,5:-1, 3:2}
p2 = Polynomial(dict2)

print p1
print p2

如果我理解你的问题,这样的事情似乎可行:

def format_term(coef, exp):
    if exp == 0:
        return "%d" % coef
    else:
        return "%dx^%d" % (coef, exp)

def format_poly(d):
    items = sorted(d.items(), reverse=True)
    terms = [format_term(v,k) for (k,v) in items]
    return " + ".join(terms)

dict1 = {0:1,1:-1}
print(format_poly(dict1))    # -1x^1 + 1

dict2 = {1:1,4:-6,5:-1, 3:2}
print(format_poly(dict2))    # -1x^5 + -6x^4 + 2x^3 + 1x^1

它只是按键对 (key,val) 对进行排序,然后格式化每个术语,并将这些术语连接成一个字符串。

  1. 删除 break 语句,因为 for 循环将在指数值等于 0.
  2. 时结束(中断)

代码:

class Polynomial(object):                                
    def __init__(self, coefficients):
        self.coefficients = coefficients

    def __str__(self):
        polytostring = ' '
        for exponent, coefficient in self.coefficients.iteritems():
            if exponent == 0:
                polytostring += '%s + ' % coefficient
            else:
                polytostring += '%sx^%s + ' % (coefficient, exponent)

        polytostring = polytostring.strip(" + ")

        return polytostring


dict1 = {0:1, 1:-1}
p1 = Polynomial(dict1)

dict2 = {1:1, 4:-6, 5:-1, 3:2}
p2 = Polynomial(dict2)

print "First:-", p1
print "Second:-", p2

输出:

$ python poly.py 
First:- 1 + -1x^1
Second:- 1x^1 + 2x^3 + -6x^4 + -1x^5

这是紧凑

def __str__(self):return"".join("%+gx^%d"%(self.coefficients[e],e)for e in sorted(self.coefficients.keys(),reverse=1))

并且工作...


让我们看一下 returned 的表达式,一次一个

"".join(...)

其中一个字符串方法是 .join(),它接受一系列字符串并将它们与(在本例中)空字符串连接起来,例如

" + ".join(["a", "b", "c"] => "a + b + c"

在我们的例子中,join 的参数是

"%+gx^%d"%(self.coefficients[e],e)for e in sorted(self.coefficients.keys(),reverse=1)

带括号的那个是 generator expression,顺便说一下,它类似于隐式 for 循环。

右边有

for e in sorted(self.coefficients.keys(),reverse=1))

即赋值给局部变量e,依次对self.coefficientskeys进行排序和倒序

左侧是生成器表达式的结果,针对 e

的每个可能值进行评估
"%+gx^%d"%(self.coefficients[e],e)

上面的表达式称为 string formatting or interpolation 像这样工作,

  1. 左边的字符串是格式字符串,其中以%为前缀的部分是_格式说明符,这里%+g 表示 generic 格式始终以符号为前缀,%d 表示 整数 ,外面的内容(此处为 `x^``)是将 vebatim 复制到结果中,

  2. 中间的%格式化运算符本身

  3. 元组(self.coefficients[e], e)是格式字符串的参数,格式说明符和参数必须一一对应

此时我们已经准备好了所有的部分......以更口语化的形式可以是

def __str__(self):
    # generated a correctly sorted list of exponents
    exps = sorted(self.coefficients.keys(),reverse=True)
    # generate a corretctly sorted list of coefficients
    coefs = [self.coefficients[e] for e in exps]
    # generate a list of formatted strings, one for each term
    reps = [ "%+gx^%d" % (c, e) for c, e in zip(coefs, exps)]
    # join the formatted strings
    poly_rep = "".join(reps)
    # let's end this story
    return poly_rep