Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials
Output:-
Print the addition of polynomials A and B.
The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0,
If co-efficient is zero then don't print the term.
If the term with highest degree is negative, the term should be represented as -Cix^Pi.
For the term where power is 1 represent it as C1x instead of C1x^1.
If the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.
For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.
Explanation
If M = 4 and 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.
def read_polynom():
  n = int(input())
  p = {}
  for i in range(n):
    L = input().split()
    Pi = int(L[0])
    Ci = int(L[1])
    p[Pi] = Ci
  return p
def add_polynomilas(p, q):
  r = {}
  Pis = set(p).union(q)
  for Pi in Pis:
    if Pi in p:
      Ci = p[Pi]
    else:
      Ci = 0.0
    if Pi in q:
      Ci += q[Pi]
    if Ci != 0.0:
      r[Pi] = Ci
  return r
def tostring_polynom(p):
  res = ''
  first = True
  for Pi in sorted(p, reverse=True):
    Ci = p[Pi]
    if first:
      if Ci == 0 and Pi == 0:
        return '0'
      Â
      if Ci == 1 and Pi != 0:
        pass
      elif Ci == -1 and Pi != 0:
        res = '-'
      else:     Â
        res = f'{Ci}'
      first = False
      Â
    else:    Â
      if Ci > 0:
        res += ' + '
      elif Ci < 0:
        res += ' - '
      else:
        continue
      res += f'{abs(Ci)}'
    Â
    if Pi == 0:
      continue
    if Pi == 1:
      res += 'x'
    else:
      res += f'x^{Pi}'
  return res
def main():
  p = read_polynom()
  q = read_polynom()
  r = add_polynomilas(p, q)
  print(f'Add {tostring_polynom(p)} to {tostring_polynom(q)}')
  print(f'results {tostring_polynom(r)}')
if __name__ == '__main__':
  main()
Comments
Leave a comment