https://www.assignmentexpert.com/homework-answers/programming-and-computer-science/python/question-175894
Even though i wrote this correctly but i am not able to get propwr output
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 add_polynomilas(p, q):
r = {}
Pis = set(p).union(q)
for Pi in Pis:
if Pi in p:
Ci = p[Pi]
else:
Ci = 0.0
if Pi in q:
Ci += q[Pi]
if Ci != 0.0:
r[Pi] = Ci
return r
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 main():
p = read_polynom()
q = read_polynom()
r = add_polynomilas(p, q)
print(f'Add {tostring_polynom(p)} to {tostring_polynom(q)}')
print(f'results {tostring_polynom(r)}')
if __name__ == '__main__':
main()
#I don't know the problem since I am not able to see your output
#So I am assuming the code isn't working at all for you
#Make sure the names of the variables and fuctions are accurate, if poosible copy and paste directly from source
#The inputs should be in the format below and note that the inputs are space seperated
4
0 5
1 0
2 10
3 6
3
0 1
1 2
2 4
Add 6x^3 + 10x^2 + 5 to 4x^2 + 2x + 1
results 6x^3 + 14x^2 + 2x + 6
Comments
Leave a comment