在Python中使用字典乘多项式

问题描述 投票:0回答:1

我想在不使用 numpy 的情况下将多项式作为字典相乘,并且在不使用外部库的情况下尽可能轻松地使用类。在这里看到了一些帖子,但他们要么使用列表、类,要么使用 numpy :/

我尝试使用以下代码:

def mlpt(p1,p2):
    p1_times_p2 = {}
    for i in p1:
        erg_coeff = p1[i]
        erg_exp   = i
        for j in p2:
            erg_coeff = erg_coeff * p2[j]
            erg_exp   = erg_exp + j
        p1_times_p2[erg_exp] = erg_coeff
    for i in p2:
        erg_coeff = p2[i]
        erg_exp   = i
        for j in p1:
            erg_coeff = erg_coeff * p1[j]
            erg_exp   = erg_exp + j
        p1_times_p2[erg_exp] = erg_coeff
    return p1_times_p2

但是,当我将两个任意多项式相乘时,我似乎没有得到正确的结果:

p1 = {2: 1}
p2 = {1: 1, 2: 1}
mlpt(p1,p2)

有人知道如何修复它吗?任何帮助将不胜感激!

python dictionary math polynomials polynomial-math
1个回答
1
投票

假设你的字典是

{exponent: coefficient}
,一个简单的选择是有两个嵌套循环来填充结果字典:

def multiply(p1, p2):
    res = {}

    for e1, c1 in p1.items():
        for e2, c2 in p2.items():
            e = e1 + e2
            res[e] = res.get(e, 0) + c1 * c2

    return res
© www.soinside.com 2019 - 2024. All rights reserved.