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 Print the addition of polynomials A and B. The format for printing polynomials is: Cix^Pi + Ci-1x^Pi-1 + .... + C1x + C0, where Pi's are powers in decreasing order, Ci is co-efficient and C0 is constant, there will be space before and after the plus or minus sign. 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.
def check_polinom(polinom):
checked = []
while polinom:
tmp = polinom.pop(0)
if polinom:
for i in range(len(polinom)-1, -1, -1):
if polinom[i][0] == tmp[0]:
tmp[1] += polinom[i][1]
polinom.pop(i)
checked.append(tmp)
return checked
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 print_polinom(polinom):
s = ''
if polinom:
if polinom[0][1] < 0:
s += '-'
polinom[0][1] = -polinom[0][1]
if polinom[0][0] == 1:
s += str(polinom[0][1]) + 'x'
elif polinom[0][0] == 0:
s += str(polinom[0][1])
else:
s += str(polinom[0][1]) + 'x^' + str(polinom[0][0])
polinom.pop(0)
for el in polinom:
if el[1] == 0:
continue
elif el[1] < 0:
s += ' - '
el[1] = -el[1]
else:
s += ' + '
if el[0] == 1:
s += str(el[1]) + 'x'
elif el[0] == 0:
s += str(el[1])
else:
s += str(el[1]) + 'x^' + str(el[0])
print(s)
def input_data():
n = int(input('N '))
a = list()
for i in range(n):
a.append(list(map(int,(input('P{} C{} '.format(i+1,i+1))).split())))
return a
a = check_polinom(input_data())
b = check_polinom(input_data())
c = add_polinoms(a,b)
print_polinom(c)
Comments
Leave a comment