我需要从类节点中随机选择2个实例:
类节点:
def __init__(self, parent = None, length_to_parent = None, name = None, left = None, right = None, internal = 1, root = 0):
self.parent = parent # parent node
self.length_to_parent = length_to_parent # length to the parent node
self.name = name # name of the node (to-be-defined name if external node(leaf), None if internal node)
self.left = left # left child
self.right = right # right child
self.internal = internal # indicate if the node is an internal node
self.root = root
我正在考虑将所有实例从节点存储到列表中,然后使用random.choose或random.shuffle从列表中随机选择2个节点。
但我不知道如何将实例存储到列表中......任何人都应该帮助!感谢
答案 0 :(得分:1)
您可以像在其他任何地方一样将实例存储在列表中。
import random
lst = []
new_node = node(parent,length... etc)
lst.append(new_node)
# assuming you have > 2 nodes:
# pick two random nodes, store in another lst
random_selection = [random.choice(lst) for x in range(2)]
你有什么具体要求吗?
答案 1 :(得分:0)
我假设这个"节点"你的是二叉树的一部分。 在这种情况下,您可以遍历树并将引用存储在运行列表中。
有些事情:
arr = []
# Perform tree traversal.
traverse(root_node, arr)
# Now, do something here with the list!
def traverse(node, arr):
# Traverse the left subtree
if(node.left is not None):
traverse(node.left, arr)
# Traverse the right subtree
if(node.right is not None):
traverse(node.right, arr)
# Append the node! It can be appended like any other item in the list.
arr.append(node)
您应该能够将节点(就像其他任何东西一样)附加到列表中,然后根据需要随机选择元素。
答案 2 :(得分:0)
我添加一个包含所有节点的类变量(在__init__
末尾添加),以及一个随机获取两个节点的类方法:
import random
class Node:
node_instances = []
def __init__(self, parent = None, length_to_parent = None, name = None, left = None, right = None, internal = 1, root = 0):
self.parent = parent # parent node
self.length_to_parent = length_to_parent # length to the parent node
self.name = name # name of the node (to-be-defined name if external node(leaf), None if internal node)
self.left = left # left child
self.right = right # right child
self.internal = internal # indicate if the node is an internal node
self.root = root
Node.node_instances.append(self)
@classmethod
def get_random_instances(cls):
return random.sample(cls.node_instances, 2)
您可以使用:
n_random = Node.get_random_instances()