Answer to Question #320559 in Python for Sai

Question #320559



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.




The format for printing polynomials is: Cix^Pi +Ci-1x*Pi-1t +C1x + CO, where Pi's are powers in decreasing order, Ci is co-efficient and CO 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 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.





Sample Input




4




05




10




2 10




3 6




3




01




12




24




Sample Output




6x3 + 14x^2 +2x + 6




O









1
Expert's answer
2022-03-30T02:50:58-0400

The following set of codes works efficiently:

# Enter polynomial dataset
print('Polynomial 1 data:')
n = int(input('Enter the number of N polynomial members: '))
polynomial_a = [0 for item in range(n)]
for item in range(n):
    p, c = input('Enter Pi and Ci separated by space: ').split(' ')
    polynomial_a[int(p)] = int(c)
print('Polynomial 2 data:')
m = int(input('Enter the number of M polynomial members: '))
polynomial_b = [0 for item in range(m)]
for item in range(m):
    p, c = input('Enter Pi and Ci separated by space: ').split(' ')
    polynomial_b[int(p)] = int(c)

# define references to polynomials of greater and lesser length
pol_max, pol_min = polynomial_a, polynomial_b
if len(pol_min) > len(pol_max):
    pol_max, pol_min = polynomial_b, polynomial_a

# add the coefficients of the polynomials pairwise
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
APPROVED BY CLIENTS