Answer to Question #237606 in Python for hithosh

Question #237606

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.


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 the degree of polynomial is zero and the constant term is also zero, then just print 0 to represent the polynomial.***veryimp

For term Cix^Pi, if the coefficient of the term Ci is 1, simply print x^Pi instead of 1x^Pi.


1
Expert's answer
2021-09-15T17:23:45-0400
def sum_polyn(pol_A, pol_B,x,y):
    S = max(x,y)
    add = [0 for row in range(S )]
    for n in range(0,x, 1):
        add[n] = pol_A[n]
    for n in range(y):
        add[n] += pol_B[n]
    return add
def display_pol(polyno, a):
    for cols in range(a):
        print(polyno[cols], end= " ")
        if (cols != 0):
            print("x^", cols, end=" ")
        if (cols != a - 1):
            print(" + ", end= " ")
Q = []
P = []
M = int(input("Input the size of the first polynomial:\t"))
n = int(input("Input the size of the second polynomial:"))
print("The elements of the second polynomial\t")
for element in range(M):
    x, y = input("Enter the power and coefficient and separate them with space\t").split(' ')
    Q.append(int(y))
print("The elements of the second polynomial\t")
for element in range(n):
    x, y = input("Enter power and coefficient and separate them with space\t").split(' ')
    P.append(int(y))
print("First polynomial is")
display_pol(P, M)
print("Second polynomial is")
display_pol(P,n)
print("\n", end=" ")
sum = sum_polyn(Q, P, M, n)
size = max(M,n)
print("Sum polynomial is"  )
import numpy as np
p = np.poly1d(sum)
print(p)

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