2015-04-06 66 views
1

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

你可以在第二个多项式中看到,如果我的最后一个常数不是一个常量,那么在安排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 
+0

什么应该被接受输出的打印语句? (:P) –

+0

'exponent.reverse()'还不够...请注意,字典的“键”不会以任何特定顺序返回。你想要的是'exponent.sort(reverse = true)' – gboffi

+0

由循环中的'exponent = i',你抛弃了'exponent'列表的内容......这是你最想要的吗? – gboffi

回答

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

代码:

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 
2

东西这样似乎工作,如果我理解你的问题:

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 

它只是排序(键,VAL)对通过键,然后格式化每个术语,并加入条款成一个字符串。

0

这是紧凑

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

和工程...


让我们来看看这是return版,一块在时间

"".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.coefficients在排序keys和反序

,并在左侧还有的结果发生器表达式,针对每个可能值进行评估e

"%+gx^%d"%(self.coefficients[e],e) 

T他表达上述被称为string formatting or interpolation 和工作原理是这样,

  1. 左边的字符串是格式字符串%前缀在它的部分是_format符,这里%+g意味着通用格式总是由符号前缀和%d装置整数位数,什么外部(这里`的x ^``)被复制vebatim到结果,

  2. %中间是格式化操作本身

  3. 元组(self.coefficients[e], e)是格式字符串的参数,你mnust有

格式说明和参数之间的1对1对应关系。在这一点上,我们有更多的地方...以更通俗的形式它可能是

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