python – Polynomial Multiplication Simplification

Question:

I am relatively new to programming and as a personal project I decided to make a calculator of basic operations of polynomials (Addition, Multiplication, Subtraction and Division) without the help of libraries in Python, currently I am stuck in the final step for Multiplication; simplification. The "L1" represents the exponent of the "x" and the "L2" represents the coefficient of the "x".

L1 = [4,3,2,3,2,1,2,1,0]
L2 = [2,3,2,4,6,4,6,9,6]

The expected result for this example would be to end up with the following lists:

L4 = [4,3,2,1,0]
L5 = [2,7,14,13,6]

What I need is to find a method to add each element of L2 that corresponds to each element of L1 repeated, that is, in the case of exponents 2:

L6 = [2,2,2]
L7 = [2,6,6]

An apology if my question is not very clear, it is the first post I make in a forum. Thanks

Answer:

A simple solution. You match the lists L1 and L2 (which must be the same length) with the zip() function in order to take pairs of values ​​(one from each list). The first value in each pair would be the exponent and the second would be the coefficient. You use the exponent as a dictionary key to add the coefficient to what is already in that dictionary key.

If you also use the defaultdict(int) (a dictionary whose values ​​are created with the default zero value at the moment they are accessed for the first time, if they don't already exist), the thing is very simple:

from collections import defaultdict

p = defaultdict(int)
for exp, coef in zip(L1, L2):
  p[exp] += coef

The result in p is a dictionary in which each key is each of the processed exponents, and each value is the result of adding the coefficients. In your example this dictionary would have:

{0: 6, 1: 13, 2: 14, 3: 7, 4: 2}

If you want to have it in two separate lists (one for exponents and one for coefficients), from highest to lowest exponent, you can separate them like this:

L4 = list(sorted(p, reverse=True))
L5 = [p[exp] for exp in L4]

And you get:

L4: [4, 3, 2, 1, 0]
L5: [2, 7, 14, 13, 6]

Without using defaultdict

The code is a bit longer because you have to verify that the key exists in the dictionary (and if not create it before accessing it):

p = {}
for exp, coef in zip(L1, L2):
  if not exp in p:
    p[exp] = 0
  p[exp]+=coef

The way to separate the result into two lists would be the same.

Scroll to Top