Answer to Question #176094 in Python for CHANDRASENA REDDY CHADA

Question #176094

Add two polynomials

Given two polynomials A and B, write a program that adds the given two polynomials A and B.


Sample Input

4

0 5

1 0

2 10

3 6

3

0 1

1 2

2 4

Sample Output

6x^3 + 14x^2 + 2x + 6


Sample Input

5

0 -2

3 6

4 7

1 -3

2 -1

5

0 1

1 2

2 -4

3 3

4 5

Sample Output

12x^4 + 9x^3 - 5x^2 - x - 1



Sample Input

5

0 2

1 0

2 1

4 7

3 6

5

2 4

3 3

4 5

0 1

1 0

Sample Output

12x^4 + 9x^3 + 5x^2 + 3


1
Expert's answer
2021-03-29T22:41:48-0400
def get_polinom():
    pol = {}
    n = int(input('Enter size polinom '))
    print('Enter the degree and value of the polynomial element separated by a space')
    for i in range(n):
        power, value = input().split(' ')
        power = int(power)
        value = float(value)
        if int(power) in pol:
            pol[power]+= value
        else:
            pol[power] = value
    return pol 

def sum_polinom(a,b):
    pol_sum ={}
    for i in a:
        if i  in pol_sum:
            pol_sum[i] += a[i]
        else:
            pol_sum[i] = a[i]
    for i in b:
        if i  in pol_sum:
            pol_sum[i] += b[i]
        else:
            pol_sum[i] = b[i]
    return pol_sum
    
def print_polinom(arg):
    for i in  sorted(arg.keys(),reverse = True):
        if arg[i] !=0 :
            if i == 0:
                print (arg[0])
            elif i == 1:
                print (f'{arg[1]}x + ',end='')
            else:
                print(f'{arg[i]}x^{i} + ',end='')
                
pol_1 = get_polinom()
pol_2 = get_polinom()
print_polinom(sum_polinom(pol_1, pol_2))
        

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