input:
5
0 -2
3 6
4 7
1 -3
expected output : 7x^4 + 6x^3 - x^2 - 3x - 2
your output: 7x^4 + 6x^3 - 1x^2 - 3x - 2
for this code this is the error
and i am using python 3.9
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
not_in = True
for i in range(len(polinom)):
if polinom[i][0] == pi:
polinom[i][1] += ci
not_in = False
break
if not_in:
polinom.append([pi, ci])
k += 1
return sorted(polinom, reverse=True, key=lambda k : k[0])
def print_polinom(polinom:list):
s = ''
if len(polinom) == 0:
pass
else:
first = True
for el in polinom:
if el[1] == 0:
continue
if el[1] < 0:
if first:
s += '-'
else:
s += ' - '
else:
if not first:
s += ' + '
first = False
if (abs(el[1]) == 1) and el[0] == 0:
s += '1'
continue
if abs(el[1]) != 1:
s += str(abs(el[1]))
if el[0] < 0:
s += 'x^({})'.format(el[0])
elif el[0] == 1:
s += 'x'
elif el[0] > 0:
s += 'x^{}'.format(el[0])
if len(s) == 0:
print('0')
else:
print(s)
print_polinom(input_polinom())
Comments
Leave a comment