我想在这里加两个多项式。多项式类在此代码之后给出。我面临的问题是将poly2转换成字典格式(第2个代码的步骤2)
def create(string):
p = Polynomial()
for word in string.split():
nums = word.split('x')
p.add_term(float(nums[0]), int(nums[1]))
return p
poly1 = create("1x3 1x4")
poly2 = create("-1x2")
poly = poly1.add(poly2)
这是多项式类:
类多项式:
def __init__(self):
self.power2coeff = {}
def add_term(self, coeff, power):
self.power2coeff[power] = coeff
def __str__(self):
result = ''
for power, coeff in self.power2coeff.items():
result += '{:.2f}x{} '.format(coeff, power)
return result
def add(self,poly2):
poly1=self.power2coeff **#STEP1**
poly2=? **#STEP2**
*code to add poly1 and poly2*
问题在于poly2变量。我怎样才能得到字典格式的呢?例如,在函数“add”中,当我按照步骤1中的方式设置poly1变量时,它是字典格式的。但我不知道怎么用同样的方法得到poly2
poly2.power2coeff为上述代码工作
相关问题 更多 >
编程相关推荐