Python程序将两个多项式相乘,其中多项式的每个项表示为一对整数(系数,指数)?
问题描述:
功能需要两个列表(具有元组作为值)作为输入 我在我的脑海中,后面的算法为此编写代码,但要正确编写它。Python程序将两个多项式相乘,其中多项式的每个项表示为一对整数(系数,指数)?
- >首先要求no。存储每个幂的系数的字典乘以多项式p2的所有系数。
然后将所有具有相同功率的字典系数相加。
def multpoly(p1,p2):
dp1=dict(map(reversed, p1))
dp2=dict(map(reversed, p2))
kdp1=list(dp1.keys())
kdp2=list(dp2.keys())
rslt={}
if len(kdp1)>=len(kdp2):
kd1=kdp1
kd2=kdp2
elif len(kdp1)<len(kdp2):
kd1=kdp2
kd2=kdp1
for n in kd2:
for m in kd1:
rslt[n]={m:0}
if len(dp1)<=len(dp2):
rslt[n][m+n]=rslt[n][m+n] + dp1[n]*dp2[m]
elif len(dp1)>len(dp2):
rslt[n][m+n]=rslt[n][m+n] + dp2[n]*dp1[m]
return(rslt)
答
如果我理解正确,您需要一个函数来乘以两个多项式并返回结果。将来,请尝试发布具体问题。下面是代码,会为你工作:
def multiply_terms(term_1, term_2):
new_c = term_1[0] * term_2[0]
new_e = term_1[1] + term_2[1]
return (new_c, new_e)
def multpoly(p1, p2):
"""
@params p1,p2 are lists of tuples where each tuple represents a pair of term coefficient and exponent
"""
# multiply terms
result_poly = []
for term_1 in p1:
for term_2 in p2:
result_poly.append(multiply_terms(term_1, term_2))
# collect like terms
collected_terms = []
exps = [term[1] for term in result_poly]
for e in exps:
count = 0
for term in result_poly:
if term[1] == e:
count += term[0]
collected_terms.append((count, e))
return collected_terms
不过请注意,肯定有更好的方式来表示这些多项式使得乘法是更快,更容易编码。与字典你的想法稍好,但仍然凌乱。您可以使用索引表示指数的列表,并且该值表示系数。例如。您可以将2x^4 + 3x + 1
表示为[1, 3, 0, 0, 2]
。
请提出具体问题。 – xnx
不清楚你问什么或你的问题是什么 –
[this]的可能重复(http://stackoverflow.com/questions/39057546/how-to-calculate-sum-of-two-polynomials/ 39058521#39058521)问题? –