Answer to Question #259295 in Python for Villan

Question #259295

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.


Output



Explanation



If M = 4 and for 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.


Then polynomial A represents "6x^3 + 10x^2 + 5", the polynomial B represents "4x^2 + 2x + 1" and the addition of A and B is "6x^3 + 14x^2 + 2x + 6"

1
Expert's answer
2021-10-31T12:02:35-0400
# enter dataset polinom
print('Plolinom A data entry')
n = int(input('Enter the number of N polynomial members '))
polinom_a =[0 for item in range(n)]
for item in range(n):
 p, c = input('Enter separated by space Pi and Ci ').split(' ')
 polinom_a[int(p)] = int(c)
m = int(input('Enter the number of M polynomial members '))
polinom_b =[0 for item in range(m)]
print('Plolinom B data entry')
for item in range(m):
 p, c = input('Enter separated by space Pi and Ci ').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]
# result output
for item in range(len(pol_max)-1,0,-1):
 if item == 0:
  continue
 print (f'{pol_max[item]}x^{item} + ',end='')
print(pol_max[0])

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog