Answer to Question #255667 in Python for Chethan

Question #255667
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-25T01:26:31-0400
def add(A, B, a, b):
    size = max(a, b)
    sum = [0 for i in range(size)]


    for i in range(0, a, 1):
        sum[i] = A[i]

    for i in range(b):
        sum[i] += B[i]

    return sum


def printPolynomial(poly, b):
    for i in range(b):
        print(poly[i], end="")
        if (i != 0):
            print("x^", i, end="")
        if (i != n - 1):
            print(" + ", end="")


# Main Funtion
if __name__ == '__main__':
    A = [5, 0, 10, 6]


    B = [1, 2, 4]
    a = len(A)
    b = len(B)


    print("Polynomial 1:")
    printPolynomial(A, a)
    print("\n", end="")
    print("Polynomial 2:")
    printPolynomial(B, b)
    print("\n", end="")
    sum = add(A, B, a, b)
    size = max(a, b)


    print("Answer:")
    printPolynomial(sum, size)

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