我努力创造__ 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
什么应该被接受输出的打印语句? (:P) –
'exponent.reverse()'还不够...请注意,字典的“键”不会以任何特定顺序返回。你想要的是'exponent.sort(reverse = true)' – gboffi
由循环中的'exponent = i',你抛弃了'exponent'列表的内容......这是你最想要的吗? – gboffi