3

For instance, 3x^4 - 17x^2 - 3x + 5. Each term of the polynomial can be represented as a pair of integers (coefficient, exponent). i.e. [(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:

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

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

Explanation: 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

smci
  • 32,567
  • 20
  • 113
  • 146

1 Answers1

2

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:

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)]
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69