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.
How to print 0 in the code for this question since i am trying this question from last 1 mnth i am not passing test casses please help me to do this
def enter_polinom():
while True:
try:
N = int(input(''))
except:
print('enter positive integer')
continue
if N < 0:
print('enter positive integer')
continue
break
P = []
k = 0
while k < N:
try:
t = list(map(int, input('').split()))
if len(t) != 2:
print('enter two integers')
continue
k += 1
except:
print('enter two integers')
continue
add = True
for i in range(len(P)):
if P[i][0] == t[0]:
P[i][1] += t[1]
add = False
if add:
P.append(t)
return P
def add_polinoms(pol_1, pol_2):
added = []
while pol_1 or pol_2:
if pol_1:
tmp = pol_1.pop(0)
for i in range(len(pol_2)):
if pol_2[i][0] == tmp[0]:
tmp[1] += pol_2[i][1]
pol_2.pop(i)
break
else:
tmp = pol_2.pop(0)
added.append(tmp)
added.sort(reverse=True)
return(added)
def polinom_to_str(p, c, first=True):
s = ''
if c == 0:
return s
if first:
if c < 0:
s += '-'
c *= -1
else:
if c < 0:
s += ' - '
c *= -1
elif c > 0:
s += ' + '
if c != 1:
s += '{}'.format(c)
if p > 1:
s += 'x^{}'.format(p)
elif p == 1:
s += 'x'
elif p < 0:
s += 'x^({})'.format(p)
elif p == 0 and c == 1:
s += '{}'.format(c)
return s
def print_polinom(p):
s = ''
for el in p:
s += polinom_to_str(el[0], el[1], len(s)==0)
if len(s) == 0:
print('0')
else:
print(s)
A = enter_polinom()
B = enter_polinom()
print_polinom(add_polinoms(A, B))
Comments
Leave a comment