首页 > 解决方案 > 链表的多项式减法计算

问题描述

我正在尝试使算法解决多项式的减法。在我的 Jupiter notebook 上,输出没有问题,但是程序评分系统给出了输出错误。所以,我想知道我的算法中是否存在错误答案或错误输出的可能性。

有四个输入

  1. 多项式 X 的项数
  2. 多项式 X
  3. 多项式 Y 的项数
  4. 多项式 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, exp, 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, exp, 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, cur.exp, 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))

请告诉我是否有任何错误答案的可能性!谢谢 :)

标签: pythonsingly-linked-listpolynomials

解决方案


推荐阅读