Python程序乘以两个多项式,其中多项式的每个项表示为一对整数(系数,指数)?

时间:2016-08-21 17:33:40

标签: python python-2.7 python-3.x

fuction采用两个列表(将元组作为值)作为输入 我想到了算法为此编写代码,但要正确编写它。

- >首先要求不。用于存储每个幂的系数的字典乘以多项式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) 

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想要一个函数乘以两个多项式并返回结果。将来,请尝试发布特定问题。以下是适用于您的代码:

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

但是请注意,肯定有更好的方法来表示这些多项式,这样乘法更快更容易编码。你对dict的想法稍微好些但仍然很混乱。您可以使用索引表示指数的列表,值表示系数。对于前者您可以将2x^4 + 3x + 1表示为[1, 3, 0, 0, 2]