Add two polynomials
Given two polynomials A and B, write a program that adds the given two polynomials A and B
Output
Print the addition of polynomials A and B.
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.
for Question and Test Cases, Inputs and Outputs See this below url link
https://drive.google.com/file/d/1dEzy0tHPt-dveknUMw8ml85IARaoLcsE/view?usp=sharing
The above url link contains Add two polynomials question and total 4 test cases, Inputs and Outputs
We need all test cases can be came when code was run. I want exact outputs for all test cases
def set_polinom():
res = {}
n = int(input())
for i in range(n):
p, v = input().split()
p = int(p)
v = int(v)
if p in res:
res[p] += v
else:
res[p] = v
return res
def sum_polinom(a,b):
res = {}
for key in a:
if key in res:
res[key] += a[key]
else:
res[key] = a[key]
for key in b:
if key in res:
res[key] += b[key]
else:
res[key] = b[key]
return res
def print_polinom(c):
if not any(list(c.values())):
print('0')
return
p_list = list(c)
p_list.sort(reverse =True)
detect_pr = False
for key in p_list:
if c[key] == 0:
continue
if detect_pr:
if c[key]>0:
print(' + ',sep='', end='')
else:
print(' - ',sep='', end='')
print(abs(c[key]),sep='', end='')
if key == 1:
print('x',sep='', end='')
if key > 1:
print('x^',key,sep='', end='')
else:
detect_pr = True
print(c[key],sep='', end='')
if key == 1:
print('x',sep='', end='')
if key > 1:
print('x^',key,sep='', end='')
a = set_polinom()
b = set_polinom()
c = sum_polinom(a, b)
print_polinom(c)
Comments
Dear Hari nadh babu, You're welcome. We are glad to be helpful. If you liked our service please press like-button beside answer field. Thank you!
Awesome. Thank you !
Leave a comment