Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B.
Input
The first line contains a single integer M.
Next M lines contain two integers Pi, Ci separated with space, where Pi denotes power and Ci denotes co-efficient of Pi for polynomial A.
After that next line contains a single integer N.
Next N lines contain two integers Pj, Cj separated with space, where Pj denotes power and Cj denotes co-efficient of Pj for polynomial B.
Output
Explanation
If M = 4 and for polynomial A
For power 0, co-efficient is 5
For power 1, co-efficient is 0
For power 2, co-efficient is 10
For power 3, co-efficient is 6.
If N = 3 and for polynomial B
For power 0, co-efficient is 1
For power 1, co-efficient is 2
For power 2, co-efficient is 4.
Then polynomial A represents "6x^3 + 10x^2 + 5", the polynomial B represents "4x^2 + 2x + 1" and the addition of A and B is "6x^3 + 14x^2 + 2x + 6"
print 0 if degree of polynomial is 0
def DispPoly(C,n):
  C = C[::-1]
  s = ""
  k=n-1
  for r in range(0,len(C)-2):
    if(r==0):
      if(C[r]>0): s = s + str(C[r])+"x^"+str(k)
      if(C[r]<0): s = s + str(C[r])+"x^"+str(k)
    if(r>0):
      if(C[r]>0): s = s + "+" + str(C[r])+"x^"+str(k)
      if(C[r]<0): s = s + str(C[r])+"x^"+str(k)
      Â
    k=k-1
  if(C[n-2]>0): s = s + "+" + str(C[n-2]) + "x"
  if(C[n-2]<0): s = s +    str(C[n-2]) + "x"
  if(C[n-1]>0): s = s + "+" + str(C[n-1])
  if(C[n-1]<0): s = s +    str(C[n-1])
  print(s)  Â
  Â
N = int(input("Enter the Order of Polynomial: "))
N = N+1
print("Enter coefficients of the two polynomiuals separated by SPACE: ")
Coeff=[]
AddP=[]
for r in range(0,N):
  s = "Enter coeff. of x^" + str(r) + str(": ")
  t = (str(input(s))).split(" ")
  temp = []
  temp.append(int(t[0]))
  temp.append(int(t[1]))
  Coeff.append(temp)
  AddP.append(sum(temp))
  Â
Coeff = np.array(Coeff)
Coeff=np.transpose(Coeff)
print("\nPolynomial-1:")
DispPoly(Coeff[0],N)
print("\nPolynomial-2:")
DispPoly(Coeff[1],N)
print("\nAfter Adding two polynomials: ")
DispPoly(AddP,N)
Comments
Leave a comment