【问题标题】:How to organize Poly and create Node如何组织 Poly 并创建 Node
【发布时间】:2021-08-23 15:27:41
【问题描述】:

在这个类中,多项式接受一个像这样的元组列表 >> [(1,2),(3,1),(2,3),(2,2)]

我需要为这个特定部分做的是获取一个元组列表,然后插入函数和 init 函数应该能够通过创建节点基于指数以升序组织数据在 Node 类中。

现在我的代码正在返回:

>>> p = Poly([(1,0),(2,2),(1,1),(3,4)])

>>> print(p)

3x^4Traceback (most recent call last):
  Python Shell, prompt 5, line 1
builtins.TypeError: __str__ returned non-string (type NoneType)

它是一个链接列表,我不允许事先组织列表或将其转换为字典或任何其他形式。它应该由 insert 和 init 函数组织。

class Poly:
    class Node:
        def __init__(self, coef, power, _next):
            self._coef = coef   #coefficient from tuple first number
            self._power = power # exponent from tuple second number
            self._next = None
        def __repr__(self):
            pass
    def __init__(self, lst):
        self._head = None
        for i in lst:
            coefficient = i[0]
            exponent = i[1]
            self._head = self.Node(coefficient, expo, self._head)

     
    def __str__(self):
        tmp = self._head
        while tmp != None :
            print(f'{tmp._coef}x^{tmp._power}')
            tmp = tmp._next
    
    def insert(self, tup):
        pass

我尝试在 Poly init 函数中创建一个 while 循环并分离两个元组编号,但我不确定从哪里开始 Node 类并且非常困惑,感谢任何帮助并谢谢提前。

输出应该是这样的:

>>> p0 = Poly([(3,2), (1,0)])

>>> print(p0) 

>>> 1 + 3x^2

>>> p1 = Poly([(0,3),(4,5),(2,3),(3,4)])

>>> print(p1)

>>> 2x^3 + 3x^4 + 4x^5

【问题讨论】:

  • 节点类很好,虽然如果你不使用它,你不需要_next作为参数。 insert 函数只需要从头开始并按数字顺序将新节点插入到适当的位置。所以如果_next不为空,且_power大于新幂,则在此处插入新记录。
  • 明白了,但是随着数据作为一个包含元组的列表传入,我将如何首先创建节点,这就是我想知道的?就像我如何告诉python第一个数字是一个系数,而元组中的第二个数字是一个幂然后交叉检查这些幂是否更大?我尝试了一个while循环,但我无法让它在没有索引错误的情况下进行迭代和比较@TimRoberts

标签: python python-3.x list function linked-list


【解决方案1】:

很难描述这个过程。您的插入器需要扫描列表,寻找 NEXT 节点比新节点具有更高功率的节点。这就是你在新条目中缝合的地方。

class Node:
    def __init__(self, coef, power, _next=None):
        self.coef = coef
        self.power = power
        self.next = _next
    def __repr__(self):
        if self.power:
            return f"{self.coef}x^{self.power}"
        return str(self.coef)

class Poly:
    def __init__(self, lst):
        self.head = None
        for i in lst:
            self.insert( i )
     
    def __str__(self):
        if not self.head:
            return "<Poly (none)>"
        nxt = self.head
        parts = []
        while nxt:
            parts.append(str(nxt))
            nxt = nxt.next
        return "<Poly " + (' + '.join(parts)) + ">"
    
    def insert(self, tup):
        node = Node(*tup)
        if not self.head:
            self.head = node
            return
        if self.head.power == node.power:
            self.head.coef += node.coef
            return
        # Loop until the NEXT node's power is larger than the new node.
        nxt = self.head
        while nxt.next and node.power > nxt.next.power:
            if node.power == nxt.power:
                nxt.coef += node.coef
                return
            nxt = nxt.next
        node.next = nxt.next
        nxt.next = node

p = Poly([(1,0),(2,2),(1,1),(3,4)])
print(p)
p = Poly([(0,3),(4,5),(2,3),(3,4)])
print(p)

输出:

<Poly 1 + 1x^1 + 2x^2 + 3x^4>
<Poly 2x^3 + 3x^4 + 4x^5>

如果“头”实际上是一个虚拟节点,代码会变得更简单一些,这样self.head.next就有了第一个数据节点:

class Poly:
    def __init__(self, lst):
        self.head = Node(-1,-1)
        for i in lst:
            self.insert( i )
     
    def __str__(self):
        nxt = self.head.next
        parts = []
        while nxt:
            parts.append(str(nxt))
            nxt = nxt.next
        return "<Poly " + (' + '.join(parts)) + ">"
    

    def insert(self, tup):
        node = Node(*tup)
        # Loop until the NEXT node's power is larger than the new node.
        nxt = self.head
        while nxt.next and node.power > nxt.next.power:
            nxt = nxt.next
        if nxt.next and node.power == nxt.next.power:
            nxt.next.coef += node.coef
        else:
            node.next = nxt.next
            nxt.next = node

【讨论】:

  • 您的代码以相反的顺序排列,我将如何按照预期的方式对其进行排序?例如,较低的权力在前,较高的权力在后。您显示的输出不是从您的代码收到的输出。
  • 我在第一个代码中显示的输出正是两个代码 sn-ps 的输出。输出以权力的递增顺序出现,这是错误的,但这就是你所要求的。如果您没有看到该结果,则说明您错误地复制了我的代码。
  • @TimeRoberts 抱歉,我的意思是说,如果您有一个实例,其中元组具有相同的功率,那么用于组合两个系数的 if 语句永远不会发生,并且它最终会跳过它。 .. [(1,0),(2,2),(1,1),(3,4),(3,2)] 最终会得到结果 &lt;Poly 1 + 1x^1 + 3x^2 + 2x^2 + 3x^4&gt; 而不是 1 + 1x^1 + 5x^2 + 3x^4
  • 啊,应该是这样,但是有一个错误。你有没有试图追赶它?第二个 sn-p 现在可以正确组合相等的功率。
  • 是的,我追了下来,你能解释一下虚拟节点的原因吗?
【解决方案2】:

为了正确排序,我首先需要实现插入函数,该函数查看我的self._power 将小于元组位置 1 的所有场景以及它大于或等价的实例......之后我可以在 __init__ 函数中循环遍历我的列表,并使用列表中的元组调用 insert(tuple) 对其进行排序。

在我的__str__ 函数中:

一开始一个简单的空字符串就足够了,在循环遍历字符串时,我可以继续添加到空字符串中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    相关资源
    最近更新 更多