gpt4 book ai didi

python - 用字典 python 漂亮地打印多项式

转载 作者:太空宇宙 更新时间:2023-11-04 10:25:33 25 4
gpt4 key购买 nike

我正在努力用多项式创建 __ str __ 函数(又名 pretty-print ),其中字典用于包含作为键的幂和作为系数的元素。我已经用列表完成了,但我还没有掌握字典。有什么需要改进的吗?

你可以在第二个多项式中看到,如果我的最后一个常数不是常数,用 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

最佳答案

如果我理解你的问题,这样的事情似乎可行:

def format_term(coef, exp):
if exp == 0:
return "%d" % coef
else:
return "%dx^%d" % (coef, exp)

def format_poly(d):
items = sorted(d.items(), reverse=True)
terms = [format_term(v,k) for (k,v) in items]
return " + ".join(terms)

dict1 = {0:1,1:-1}
print(format_poly(dict1)) # -1x^1 + 1

dict2 = {1:1,4:-6,5:-1, 3:2}
print(format_poly(dict2)) # -1x^5 + -6x^4 + 2x^3 + 1x^1

它只是按键对 (key,val) 对进行排序,然后格式化每个术语,并将这些术语连接成一个字符串。

关于python - 用字典 python 漂亮地打印多项式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29473533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com