在 Python 中对列表中的新对象进行排序
Sorting new objects inside an list in Python
我想寻求一些帮助。
我有一个多项式对象,我已经为它建立了数学等式。
例如,如果我有 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 []
如果您的二叉树中的多项式已经按正确的顺序排列(您应该这样做),那么您只需读取所有节点 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)
我想寻求一些帮助。 我有一个多项式对象,我已经为它建立了数学等式。 例如,如果我有 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 []
如果您的二叉树中的多项式已经按正确的顺序排列(您应该这样做),那么您只需读取所有节点 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)