[英]Adding two polynomials in python
I am trying to add two polynomials here.我想在这里添加两个多项式。 The polynomial class is given after this code.
在这段代码之后给出了多项式类。 The problem I am facing is getting poly2 into a dictionary format (STEP 2 of the 2nd code)
我面临的问题是将 poly2 转换为字典格式(第二个代码的第 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)
This is the Polynomial class:这是多项式类:
class Polynomial:类多项式:
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*
The problem is with the poly2 variable.问题在于 poly2 变量。 How do I get it in dictionary format?
我如何以字典格式获取它? For example, in the function "add", the poly1 variable is in dictionary format when I set it the way it is in step1.
例如,在函数“add”中,poly1 变量在我按照 step1 中的方式设置时采用字典格式。 But I cannot figure out how to get poly2 the same way.
但我不知道如何以同样的方式获得 poly2。
poly2.power2coeff 适用于上述代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.