简体   繁体   English

如何使用python 3.x执行多项式加法和乘法?

[英]How to perform polynomial addition and multiplication using python 3.x?

For instance, 3x^4 - 17x^2 - 3x + 5 . 例如3x^4 - 17x^2 - 3x + 5 Each term of the polynomial can be represented as a pair of integers (coefficient, exponent). 多项式的每个项可以表示为一对整数(系数,指数)。 ie [(3,4),(-17,2), (-3,1), (5,0)] [(3,4),(-17,2), (-3,1), (5,0)]

We have the following constraints to guarantee that each polynomial has a unique representation: 我们具有以下约束条件,以确保每个多项式都有唯一的表示形式:

  • Terms are sorted in descending order of exponent 术语按指数的降序排列
  • No term has a zero cofficient 没有一项的系数为零
  • No two terms have the same exponent 没有两个术语具有相同的指数
  • Exponents are always nonnegative 指数总是非负的

Write Python functions for the following operations: 为以下操作编写Python函数:

addpoly(p1,p2)
multpoly(p1,p2)

Some examples: 一些例子:

>>> addpoly( [(4,3),(3,0)], [(-4,3),(2,1)] )
[(2, 1),(3, 0)]

Explanation: (4x^3 + 3) + (-4x^3 + 2x) = 2x + 3 说明: (4x^3 + 3) + (-4x^3 + 2x) = 2x + 3

>>> addpoly( [(2,1)], [(-2,1)] )
[]

Explanation: 2x + (-2x) = 0 说明: 2x + (-2x) = 0

>>> multpoly( [(1,1),(-1,0)], [(1,2),(1,1),(1,0)] )
[(1, 3),(-1, 0)]

Explanation: (x - 1) * (x^2 + x + 1) = x^3 - 1 说明: (x - 1) * (x^2 + x + 1) = x^3 - 1

You want to define a function that takes an arbitrary amount of arguments of the form 您想定义一个函数,该函数接受任意数量的形式的参数

[(4,3),(3,0)], [(-4,3),(2,1)]

addpoly could be done easily with a collections.defaultdict : addpoly可以通过collections.defaultdict轻松完成:

from collections import defaultdict

def addpoly(*polynoms):
    result = defaultdict(int)
    for polynom in polynoms:
        for factor, exponent in polynom:
            result[exponent] += factor
    return [(coeff, exponent) for exponent, coeff in result.items() if coeff]
In [68]: addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
Out[68]: [(3, 0), (2, 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM