Answer to Question #242073 in Python for bannu

Question #242073

For this question

Add two polynomials

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

if the in puts are

4

0 5

1 0

2 10

3 6

4

0 -5

1 0

2 -10

3 -6

then the result is 0 but it is not showing the result from the code of Question #175894



1
Expert's answer
2021-09-25T05:20:51-0400
def get_polinom():
    res =[]
    n = int(input('Enter the number of lines of the polynomial: '))
    for _ in range(n):
        pow_el, value_el = input(
        'Enter the int power and int value of the polynomial element:').split()
        res.append([int(pow_el), int(value_el)])
    return res 


def polinom_print(arg):
    pol ={}
    # We form a dictionary if there are elements with the same power, add
    for item in arg:
        pol[item[0]] = pol.get(item[0], 0) + item[1]
    # Create a line string  to output the polynomial
    pol_str = ''
    for key in sorted(pol.keys(), reverse=True):
        if pol[key] == 0:
            continue
        if key == 1:
            pol_str += f'{pol[key]:+d}x'
        elif key == 0:
            pol_str += f'{pol[key]:+d}'
        else:
            pol_str += f'{pol[key]:+d}x^{key}'
    if pol_str:
        print(pol_str)
    else:
        print(0)
   
# the polynomial is presented as a list
# [[pow_1,value_1],...[pow_n,value_n]]
A = get_polinom()
B = get_polinom()
C = A + B
polinom_print(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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS