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.
if sum of polynimials is zero, the output will be "0"
M = int(input('Enter the number of M polynomial members: '))
polinom_a =[0 for item in range(M)]
print('Plolinom A data entry')
for item in range(M):
p, c = input('Enter 2 integers separated by space Pi and Ci: ').split(' ')
polinom_a[int(p)] = int(c)
N = int(input('Enter the number of N polynomial members: '))
polinom_b =[0 for item in range(N)]
print('Plolinom B data entry')
for item in range(N):
p, c = input('Enter 2 integers separated by space Pj and Cj: ').split(' ')
polinom_b[int(p)] = int(c)
# define references to polynomials of greater and lesser length
pol_max , pol_min = polinom_a , polinom_b
if len(pol_min) > len(pol_max):
pol_max , pol_min = polinom_b , polinom_a
# add the coefficients of the polynorms in pairs
for item in range(len(pol_min)):
pol_max[item] += pol_min[item]
# print sum of polynomials
first = True
for index in range(len(pol_max)-1,-1,-1):
if first:
#if sum of polynimials is zero, the output will be "0"
if pol_max[index]==0 and index == 0:
print('0')
break
if pol_max[index]==1 and index != 0:
pass
#If the term with highest degree is negative, the term should be represented as -Cix^Pi.
elif pol_max[index]==-1 and index != 0:
print('-', end='')
#if coeffiecient is 0 don't print the term
elif pol_max[index]==0 and index != 0:
continue
else:
print(f'{pol_max[index]}', end='')
first = False
else:
if pol_max[index]>0:
print(' + ', end='')
# If the term with highest degree is negative, the term should be represented as -Cix^Pi.
elif pol_max[index]<0:
print(' - ', end = '')
else:
continue
print(f'{abs(pol_max[index])}', end='')
if index == 0:
continue
#For the term where power is 1 represent it as C1x instead of C1x^1.
if index == 1:
print('x', end='')
else:
print(f'x^{index}', end='')
print()
My output:
Comments
Leave a comment