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

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?

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

解决方案Remove break statement because for loop will end(break) when exponent value is equal to 0.

code:

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

Output:

$ python poly.py

First:- 1 + -1x^1

Second:- 1x^1 + 2x^3 + -6x^4 + -1x^5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值