the out put should be 12x^4 + 9x^3 - 5x^2 - x - 1 but our code does not give this out put
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
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 main():
p = read_polynom()
res = tostring_polynom(p)
final_res = ""
count = 0
vals = res.split("+")
for val in vals:
if "x" in val:
test_val = int(val.split("x")[0])
if test_val==1:
if count ==0:
final_res=final_res+val.replace("1","")
else:
final_res=final_res+"+"+val.replace("1","")
else:
if count==0:
final_res = final_res +str(val)
else:
final_res =final_res+ "+"+str(val)
count+=1
else:
final_res =final_res+ "+"+str(val)
count+=1
print(final_res)
if __name__ == '__main__':
main()
Question is not given. I just created one question where we can input number and print polynomial.
Sample Input Output
4
0 5
1 0
2 10
3 6
6x^3 + 10x^2 + 5
Comments
Leave a comment