n = int(input())
polinom_a =[0 for item in range(n)]
for item in range(n):
p, c = input().split(' ')
polinom_a[int(p)] = int(c)
m = int(input())
polinom_b =[0 for item in range(m)]
for item in range(m):
p, c = input().split(' ')
polinom_b[int(p)] = int(c)
pol_max , pol_min = polinom_a , polinom_b
if len(pol_min) > len(pol_max):
pol_max , pol_min = polinom_b , polinom_a
for item in range(len(pol_min)):
pol_max[item] += pol_min[item]
for item in range(len(pol_max)-1,0,-1):
if item == 0:
continue
print (f'{pol_max[item]}x^{item} + ',end='')
print(pol_max[0])
ouput:6x^3 + 14x^2 + 2x^1 + 6
the ouput should be like this:6x^3 + 14x^2 + 2x + 6
after adding two polynomials when we get "0" as output and it should print output as:"0"
so,please can anyone make correct code?
polinom = {}
for i in range(2):
n = int(input('n '))
for item in range(n):
p, c = input('p c ').split(' ')
p, c = int(p), int(c)
if p in polinom:
polinom[p] += c
else:
polinom[p] = c
res = ''
if len(polinom) == 0:
pass
else:
flag = True
for p in polinom:
if polinom[p] == 0:
continue
if polinom[p] < 0:
if flag:
res += '-'
else:
res += ' - '
else:
if not flag:
res += ' + '
flag = False
if (abs(polinom[p]) == 1) and p == 0:
res += '1'
continue
if abs(polinom[p]) != 1:
res += str(abs(polinom[p]))
if p < 0:
res += 'x^({})'.format(p)
elif p == 1:
res += 'x'
elif p > 0:
res += 'x^{}'.format(p)
if len(res) == 0:
print('0')
else:
print(res)
Comments
Leave a comment