-1

I want to add and multiply two polynomials. A function takes two arguments like add([(4,3),(3,0)],[(-4,3),(2,1)]).So, the polynomial looks like

  1. 4x^3 + 3 and -4x^3 + 2x

I want to add and multiply both these two polynomials without using any library.

Avijit Majhi
  • 508
  • 9
  • 15

2 Answers2

2

I have created a simplified version for both addition and multiplication by creating a blank list that can store the coefficients from constant terms to the co-eff of highest exponents. The logic is simply to update the coefficients and creating a list containing tuple pairs of the format (co-eff, exponent)

def add(p1,p2):
    x = [0]*(max(p1[0][1],p2[0][1])+1)
    for i in p1+p2:
        x[i[1]]+=i[0]
    res =  [(x[i],i) for i in range(len(x)) if x[i]!=0]
    res.sort(key = lambda r: r[1], reverse= True)
    return res

def mul(p1,p2):
    x = [0]*(p1[0][1]*p2[0][1]+1)
    for i in p1:
        for j in p2:
            x[i[1]+j[1]]+=i[0]*j[0]
    res = [(x[i],i) for i in range(len(x)) if x[i]!=0]
    res.sort(key = lambda r: r[1], reverse= True)
    return res

pls note that this code works only for non negative exponents

addition and multiplication of the polynomials you referred in the question yields the following results

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

mul([(4,3),(3,0)],[(-4,3),(2,1)]) = [(-16, 6), (8, 4), (-12, 3), (6, 1)]

0

For addition I have written a method

def poly_add( x, y):
  r = []
  min_len = min( len(x), len(y))
  for i in range(min_len):
    if x[i][1] == y[i][1]:
      m = x[i][0] + y[i][0]
      if m != 0:
        r.append((m, x[i][1])) 
    if x[i][1] != y[i][1]:
      r.append((y[i]))
      r.append((x[i]))
  return r
Avijit Majhi
  • 508
  • 9
  • 15