【问题标题】:Sorting new objects inside an list in Python在 Python 中对列表中的新对象进行排序
【发布时间】:2021-01-04 08:31:29
【问题描述】:

我想寻求一些帮助。 我有一个多项式对象,我已经为它建立了数学等式。 所以举个例子,如果我有3X^3+2X^2+X和6X^3+5X^2+4X,那么P2>P1,到目前为止一切都很好。

所有这些对象都放在 BinarySearchTree 中,并且使用 def,我需要在数组中按顺序取出它们,例如: 0 3X^3+2X^2+X 18 将释放 [0, 18, 3X^3+2X^2+X] 我设法将其中的所有多项式组成一个数组,但我不知道如何将它们直接发送到已经正确排列的数组中,或者如何对数组中的函数进行排序?

class Node:
    def inorder(self, fin_list):
        if self:
            fin_list.append(self.value)
            if self.left:
                self.left.inorder(fin_list)
            if self.right:
                self.right.inorder(fin_list)
        return list(fin_list)
class BST:
    def inorder(self):
        if self.head:
            return self.head.inorder([])
        else:
            return []

【问题讨论】:

    标签: python sorting oop object binary-search-tree


    【解决方案1】:

    如果您的 BinaryTree 中的多项式已经按正确顺序排列(您应该这样做),那么您只需读取所有节点 in-order,也称为 按顺序遍历,或左节点右遍历(LNR)。您可以通过稍微更改 inorder 函数来做到这一点:

    def inorder(self, fin_list):
        if self:
    
            # start with left child
            if self.left:
                # self.left.inorder() returns a list, and you need to add it to the existing list
                fin_list += self.left.inorder(fin_list)
    
            # then add value of current node
            fin_list.append(self.value)
    
            # finish with the right child
            if self.right:
                # self.left.inorder() returns a list, and you need to add it to the existing list
                fin_list += self.right.inorder(fin_list)
    
        return list(fin_list)
    

    【讨论】:

    • 非常感谢您的帮助!我实际上早些时候尝试过这样做,但由于某种原因它不起作用。另一方面,我确实找到了解决问题的方法。 Sorted() 函数似乎适用于对象,如果像我所做的那样,程序员为对象本身添加数学函数,以便他能够比较它们。我所要做的就是在最后添加 Sorted(fin_list)
    • @D.Z.如果您像示例中一样阅读所有内容,然后将最终列表排序为其他操作,那么您将不必要地浪费时间和资源。二叉树的全部目的是快速读取(例如按顺序)之类的操作。您正在快速读取所有数据 O(log(n)),但顺序错误,python sorted() 函数在 O(n log(n))我>。所以就我而言,你正在做一些不必要的工作。只需以正确的顺序读取您的数据。将数据插入二叉树时,您已经对数据进行了排序。顺便说一句,您会考虑将我的答案标记为正确吗?
    • 感谢您的评论和进一步的解释。我还是编程新手,所以我一定会随着时间的推移而改进(并变得更有效率)。抱歉,我没有接受答案,但现在是 :) 祝你有美好的一天!
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    相关资源
    最近更新 更多