Answer to Question #206080 in Python for Ayushi

Question #206080


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



input:

4

0 5

1 0

2 10

3 6

4

0 -5

1 0

2 -10

3 -6


expected output:



your output:


(nothing)




input:

4

0 5

1 0

2 10

3 6

3

0 1

1 2

2 4


output:


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


Errors/Warnings:

Traceback (most recent call last):

 File "main.py", line 69, in <module>

  a = input_polinom()

 File "main.py", line 2, in input_polinom

  n = int(input())

EOFError: EOF when reading a line


expected output:

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



1
Expert's answer
2021-06-13T00:03:52-0400
#python 3.9.5


def read_polynom():
    n = int(input())
    p = {}
    for i in range(n):
        L = input().split()
        Pi = int(L[0])
        Ci = int(L[1])
        p[Pi] = Ci
    return p


def add_polynomilas(p, q):
    r = {}
    Pis = set(p).union(q)
    for Pi in Pis:
        if Pi in p:
            Ci = p[Pi]
        else:
            Ci = 0.0
        if Pi in q:
            Ci += q[Pi]
        if Ci != 0.0:
            r[Pi] = Ci
    return r


def tostring_polynom(p):
    res = ''
    first = True
    for Pi in sorted(p, reverse=True):
        Ci = p[Pi]
        if first:
            if Ci == 0 and Pi == 0:
                return '0'
            
            if Ci == 1 and Pi != 0:
                pass
            elif Ci == -1 and Pi != 0:
                res = '-'
            else:           
                res = f'{Ci}'
            first = False
            
        else:        
            if Ci > 0:
                res += ' + '
            elif Ci < 0:
                res += ' - '
            else:
                continue
            res += f'{abs(Ci)}'
        
        if Pi == 0:
            continue
        if Pi == 1:
            res += 'x'
        else:
            res += f'x^{Pi}'
    return res


PiCi1 = read_polynom()
PiCi2 = read_polynom()


final_list = add_polynomilas(PiCi1, PiCi2)


print(f'Add {tostring_polynom(PiCi1)} to {tostring_polynom(PiCi2)}')
if not final_list:
    print('Results: 0')
else:
    print(f'Results: {tostring_polynom(final_list)}')

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