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)
please rectify this issue!!
def input_polinom():
n = int(input())
polinom = {}
k = 0
while k < n:
try:
pi, ci = input().split()
pi, ci = int(pi), int(ci)
except ValueError:
continue
if pi in polinom:
polinom[pi] += ci
else:
polinom[pi] = ci
k += 1
return polinom
def summ_polinoms(A:dict, B:dict):
for key in B:
if key in A:
A[key] += B[key]
else:
A[key] = B[key]
C = {}
for k in sorted(A.keys(), reverse=True):
C[k] = A[k]
return C
def print_polinom(polinom:dict):
s = ''
if len(polinom) == 0:
pass
else:
first = True
for p in polinom:
if polinom[p] == 0:
continue
if polinom[p] < 0:
if first:
s += '-'
else:
s += ' - '
else:
if not first:
s += ' + '
first = False
if (abs(polinom[p]) == 1) and p == 0:
s += '1'
continue
if abs(polinom[p]) != 1:
s += str(abs(polinom[p]))
if p < 0:
s += 'x^({})'.format(p)
elif p == 1:
s += 'x'
elif p > 0:
s += 'x^{}'.format(p)
if len(s) == 0:
print('0')
else:
print(s)
for i in range(3):
a = input_polinom()
b = input_polinom()
c = summ_polinoms(a, b)
print_polinom(c)
Comments
Leave a comment