← 返回题库
初级

A+B for Polynomials

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve(p1, p2):
    from collections import defaultdict
    poly = defaultdict(float)
    for term in p1.split(';'):
        parts = term.split(',')
        coef, exp = float(parts[0]), int(parts[1])
        poly[exp] += coef
    for term in p2.split(';'):
        parts = term.split(',')
        coef, exp = float(parts[0]), int(parts[1])
        poly[exp] += coef
    exp_sorted = sorted(poly.keys(), reverse=True)
    result = []
    for e in exp_sorted:
        if abs(poly[e]) > 0.001:
            result.append((e, poly[e]))
    output = [str(len(result))]
    for e, c in result:
        output.append(f'{e} {c:.1f}')
    print(' '.join(output))

示例

输入
solve('1,2;2,1;3,0', '2,2;3,1;4,0')
期望输出
3 2 3.0 1 5.0 0 7.0
Python 代码 🔒 登录后使用
🔒

登录后即可练习

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