使用python进行多项式加法

时间:2018-10-02 08:12:28

标签: python math

假设多项式P_A(x,5)= x ^ 5 + 2x ^ 4 + 8x ^ 2 + 9x ^ 1 + 3,可以分解为两个列表,exp = [5,4,2,1, 0]和coeff = [1,2,8,9,0]。

我想编写一个函数,该函数可以将四个列表作为输入,例如:add_coefficient(exp1,coeff1,exp2,coeff2)并按相对于相应指数的顺序返回系数列表,这只是exp1和exp2的排序集。我该如何实施?我在考虑collections.counter()或while循环,但无法开始。

1 个答案:

答案 0 :(得分:0)

There's probably more computationally efficient ways of doing it, but I'd iterate through each list storing the results in a dictionary, which seems to me to be the natural way to handle this relationship in Python.

exp_1 = [5,3,2,4] 
coeff_1 = [1,1,1,1]
exp_2 = [5,3,2,1] 
coeff_2 = [1,1,1,1]

def add_coefficient(exp1, coeff1, exp2, coeff2):
    exponent_coefficient_dict = dict()
    # Iterate through first pair of lists, storing as exp:coeff pairs.
    for index, exponent in enumerate(exp1):
        exponent_coefficient_dict[exponent] = coeff1[index]
    # Iterate through second pair of lists, storing or updating pairs.
    for index, exponent in enumerate(exp2):
        exponent_coefficient_dict[exponent] = exponent_coefficient_dict.get(exponent, 0) + coeff2[index]

    # Get a sorted list of the keys from the dictionary.
    combined_exp_list = sorted(exponent_coefficient_dict, reverse=True)
    combined_coeff_list = []

    # Populate a list for the coefficients according to the order 
    # the exponents appear in.
    for exponent in combined_exp_list:
        combined_coeff_list.append(exponent_coefficient_dict.get(exponent, 0))

    return (combined_exp_list, combined_coeff_list)

add_coefficient(exp_1, coeff_1, exp_2, coeff_2)