Answer to Question #191719 in Python for Hari nadh babu

Question #191719

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.

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.


for Question and Test Cases, Inputs and Outputs See this below url link


https://drive.google.com/file/d/1dEzy0tHPt-dveknUMw8ml85IARaoLcsE/view?usp=sharing


The above url link contains Add two polynomials question and total 4 test cases, Inputs and Outputs


We need all test cases can be came when code was run. I want exact outputs for all test cases


1
Expert's answer
2021-05-11T09:59:38-0400
def set_polinom():
    res = {}
    n = int(input())
    for i in range(n):
        p, v = input().split()
        p = int(p)
        v = int(v)
        if p in res:
            res[p] += v
        else:
            res[p] = v
    return res
       
        
def sum_polinom(a,b):
    res = {}
    for key in a:
        if key in res:
            res[key] += a[key]
        else:
            res[key] = a[key]
    for key in b:
        if key in res:
            res[key] += b[key]
        else:
            res[key] = b[key]
    return res
     
   
def print_polinom(c):
    if not any(list(c.values())):
        print('0')
        return
    p_list = list(c)
    p_list.sort(reverse =True)
    detect_pr = False
    for key in p_list:
        if c[key] == 0:
            continue
        if detect_pr:
            if c[key]>0:
                print(' + ',sep='', end='')
            else:
                print(' - ',sep='', end='')
            print(abs(c[key]),sep='', end='')
            if key == 1:
                print('x',sep='', end='')
            if key > 1:
                print('x^',key,sep='', end='')
        else:
            detect_pr = True
            print(c[key],sep='', end='')
            if key == 1:
                print('x',sep='', end='')
            if key > 1:
                print('x^',key,sep='', end='')
                
a = set_polinom()
b = set_polinom()
c = sum_polinom(a, b)
print_polinom(c)

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

Assignment Expert
12.05.21, 14:02

Dear Hari nadh babu, You're welcome. We are glad to be helpful. If you liked our service please press like-button beside answer field. Thank you!

Hari nadh babu
12.05.21, 13:21

Awesome. Thank you !

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS