相当打印多项式与字典python

时间:2015-04-06 14:45:30

标签: python dictionary polynomials

我正在努力用多项式创建__ 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

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:2)

  1. 删除中断语句,因为当指数值等于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
    

答案 2 :(得分:0)

这是 compact

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

并且有效......


让我们看看return ed的表达式,一次一件

"".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,即btw,类似于隐式for循环。

右边有

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

依次按顺序和反向顺序分配给本地变量e keys self.coefficients

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

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

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

  1. 左侧的字符串是格式字符串,其中以%为前缀的部分是_format说明符,此处%+g表示 generic < / em>格式总是以符号为前缀,而%d表示整数位,外面是什么(这里是`x ^``)被逐字复制到结果中,

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

  3. 元组(self.coefficients[e], e)是格式字符串的参数,格式说明符和参数之间只有1对1的对应关系

  4. 此时我们已经准备好所有部分......以更通俗的形式,它可能是

    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