漂亮的打印多项式与字典python [英] Pretty printing polynomials with dictionary python

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

问题描述

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

I'm struggling to create the __ str __ function (aka pretty print) with polynomials, where dictionaries are used to contain the powers as keys and the elements as coefficients. I have done it with lists but I haven't mastered dictionaries yet. Is there anything to improve?

您可以在第二个多项式中看到,如果我的最后一个常数不是常数,则在将键与一起排列后reverse()函数,加号始终存在,我该怎么做才能防止这种情况?顺便说一下,我尝试重载运算符,完成此操作后,我将尝试执行 __ add __ __ mul __ __ sub __ __ call __ ...虽然我会先完成一个:P

You can see in the second polynomial that if my last constant is not a constant, after arranging the keys with the reverse() function, the plus is always there, what can i do to prevent that? By the way I am trying to overload operators, after I've done this I'll try to do __ add__, __ mul__, __ sub__, and __ call__... though I would finish this one first :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


推荐答案


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

  1. Remove break statement because for loop will end(break) when exponent value is equal to 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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆