如何解决带链表的多项式减法计算
我正在尝试使算法解决多项式的减法。 在我的Jupiter notebook上,输出没有问题,但是程序评分系统给出了输出错误。 所以,我想知道我的算法中是否存在错误答案或错误输出的可能性。
有四个输入
- 多项式 X 的项数
- 多项式 X
- 多项式 Y 的项数
- 多项式 Y
例如, 什么时候 多项式 X = 6x^4 - 5x^2 + 3x^1
和多项式 Y = 5x^2 + 2x^1 -4,
输入是
3
6 4 -5 2 3 1
3
5 2 2 1 -4 0
然后,
我想打印减法结果,前面有空格。
因此输出(减法的结果:6x^4 - 10x^2 + x^1 + 4)将是
" "6 4 -10 2 1 1 4
这是我的算法。
class getNode:
def __init__(self,coef=None,exp=None,link=None):
self.head = None
self.coef = coef
self.exp = exp
self.next = None
self.size = 0
def append (self,coef,exp,link=None):
if self.size == 0:
self.head = getNode(coef,link)
self.coef = coef
self.exp = exp
self.next = link
self.size += 1
else:
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = getNode(coef,link)
self.coef = coef
self.exp = exp
self.next = link
self.size += 1
def print_nd(self):
print(" ",end='')
cur = self.head
while cur.next != None:
if cur.exp != 0:
print(cur.coef,cur.exp,end=' ')
cur = cur.next
else:
print(cur.coef,end=' ')
cur = cur.next
if cur.exp != 0:
print(cur.coef,end=' ')
else:
print(cur.coef,end=' ')
return ""
a = int(input())
X = list(map(int,input().split( )))
b = int(input())
Y = list(map(int,input().split( )))
def subPoly(X,Y):
x = getNode()
y = getNode()
result = getNode()
global a
global b
for i in range(0,(a*2),2):
x.append(X[i],X[i+1])
for j in range(0,(b*2),2):
y.append(Y[j],Y[j+1])
while (x.head != None and y.head != None):
if (x.head.exp > y.head.exp):
result.append(x.head.coef,x.head.exp)
x.head = x.head.next
elif (x.head.exp < y.head.exp):
result.append((-y.head.coef),y.head.exp)
y.head = y.head.next
else:
diff = x.head.coef - y.head.coef
if (diff != 0):
result.append(diff,x.head.exp)
x.head = x.head.next
y.head = y.head.next
else:
x.head = x.head.next
y.head = y.head.next
while (x.head != None):
result.append(x.head.coef,x.head.exp)
x.head = x.head.next
while (y.head != None):
result.append(-y.head.coef,y.head.exp)
y.head = y.head.next
return result.print_nd()
if (a*2==len(X) and b*2==len(Y)):
print(subPoly(X,Y))
请告诉我是否有任何错误答案的可能性!谢谢:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。