我正在努力创建__ 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
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] 删除。
我来说两句