漂亮的打印多项式与字典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
Vivek貂
  1. 删除break语句,因为for当指数值等于时,循环将结束(break)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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

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

来自分类Dev

python中的漂亮多项式打印

来自分类Dev

打印多项式的导数 - python

来自分类Dev

使用字典将Python中的多项式相乘

来自分类Dev

在python中以可变格式打印多项式

来自分类Dev

Python中的多项式除法

来自分类Dev

勒让德多项式Python

来自分类Dev

python多个变量的多项式包

来自分类Dev

Python中的多项式除法

来自分类Dev

使用python进行多项式加法

来自分类Dev

多项式类

来自分类Dev

多项式比近似

来自分类Dev

零零多项式

来自分类Dev

多项式模拟

来自分类Dev

多项式操作

来自分类Dev

Python:字符串格式与枚举一起吗?(以pythonic方式生成多项式的漂亮字符串表示形式)

来自分类Dev

将多项式回归从R移植到python

来自分类Dev

如何通过python查找矩阵的特征多项式?

来自分类Dev

Python:SciPy.interpolate分段多项式

来自分类Dev

如何从python / Sage中的多项式中提取变量

来自分类Dev

等价于Python中2D多项式的`polyfit`

来自分类Dev

Python使多项式适合3d数据

来自分类Dev

Python多项式的根不正确

来自分类Dev

Python:分段多项式曲线拟合指数

来自分类Dev

Python多项式回归绘图错误吗?

来自分类Dev

在python中查找切比雪夫多项式的根

来自分类Dev

Python-从转折点坐标生成多项式

来自分类Dev

调整Python中逻辑回归的多项式特征

来自分类Dev

Python的两个多项式的总和