假设一个多项式,P_A(x, 5) = x^5 + 2x^4 + 8x^2 + 9x^1 + 3,可以分解成两个列表,exp = [5,4,2,1,0] 和系数 = [1,2,8,9,0]。
我想编写一个可以将四个列表作为输入的函数,例如: add_coefficient(exp1, coeff1, exp2, coeff2) 并按照相对于相应指数的顺序返回系数列表,这只是一个排序集exp1 和 exp2。我该如何实施?我正在考虑 collections.counter() 或 while 循环,但无法开始。
可能有更高效的计算方法,但我会遍历每个列表,将结果存储在字典中,这在我看来是在 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句