← 返回题库
初级

Product of Polynomials

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve(p1, p2):
    from collections import defaultdict
    def parse(p):
        terms = {}
        for t in str(p).split(";"):
            c, e = t.split(",")
            terms[int(e)] = float(c)
        return terms
    t1 = parse(p1)
    t2 = parse(p2)
    poly = defaultdict(float)
    for e1, c1 in t1.items():
        for e2, c2 in t2.items():
            poly[e1 + e2] += c1 * c2
    result = [(e, poly[e]) for e in sorted(poly.keys(), reverse=True) if abs(poly[e]) > 1e-9]
    parts = [str(len(result))]
    for e, c in result:
        parts.append(str(e))
        parts.append(f"{c:.1f}")
    print(" ".join(parts))

示例

输入
2,1;2,0|2,1;2,0
期望输出
3 2 4.0 1 8.0 0 4.0
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码