本文整理汇总了Python中node.Node.left方法的典型用法代码示例。如果您正苦于以下问题:Python Node.left方法的具体用法?Python Node.left怎么用?Python Node.left使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类node.Node
的用法示例。
在下文中一共展示了Node.left方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: make_tree
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def make_tree(preorder, inorder):
'''(list, list) -> Node
Return the root of the tree described by the lists.'''
#if its an empty tree return None
if preorder == [] or inorder == []:
return None
root = preorder[0]
index = inorder.index(root)
root_node = Node(preorder[0])
#if both subtrees are empty
if len(preorder) == 1:
return root_node
#if the left subtree is not empty
if inorder.index(preorder[1]) < inorder.index(preorder[0]):
root_node.left = make_tree(preorder[1: index + 1], inorder[:index])
inorder_right_subtree = []
for item in inorder:
inorder_right_subtree.append(item)
for count in range(len(preorder)):
#if the item is not the root or on the left subtree
#then count is the index of the root of the right subtree
if inorder.index(preorder[count]) > index:
root_node.right = make_tree(preorder[count:], \
inorder_right_subtree)
break
else:
#removes the root and left subtree, so that
#inorder_right_subtree is an inorder list for the right subtree
inorder_right_subtree.remove(preorder[count])
#if the left subtree is empty
elif inorder.index(preorder[1]) > inorder.index(preorder[0]):
if len(preorder) == 2:
root_node.right = Node(preorder[1])
return root_node
root_node.right = make_tree(preorder[index + 1:], inorder[index + 1:])
inorder_left_subtree = []
for item in inorder:
inorder_left_subtree.append(item)
for count in range(len(preorder)):
#if the item is not the root or on the right subtree
#then count is the index of the root of the left subtree
if inorder.index(preorder[count]) < index:
root_node.left = make_tree(preorder[count:], \
inorder_left_subtree)
break
#removes the root and right subtree, so that inorder_left_subtree
#is an inorder list for the left subtree
else:
inorder_left_subtree.remove(preorder[count])
return root_node
示例2: arraytoBST
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def arraytoBST(array):
"""Convert a sorted array into a minimum height BST."""
if not array:
return None
middle = len(array) / 2
node = Node(key=array[middle])
node.left = arraytoBST(array[:middle])
node.right = arraytoBST(array[middle+1:])
return node
示例3: main
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def main(args):
print "Parse Tree..."
if ( len( args ) < 2 ):
print "Usage ./parse_tree.py 'List of arguments in string'"
sys.exit(-1)
print "Arguments:[ " + args[1] + " ]"
tokens = args[1].split()
z = Node()
z.left = z
z.right = z
stack = Stack()
stack.print_stack()
root = None
for token in tokens:
print token
x = Node()
x.value = token
# If the token is an operator. Pop and set the right link
# then pop and set the left link then push the token on the stack.
# Otherwise, push the token on to the stack.
if token == '+' or token == '*':
x.right = stack.pop()
print "Poping " + x.right.value + " from the stack and set to right link of " + token
x.left = stack.pop()
print "Poping " + x.left.value + " from the stack and set to left link of " + token
print "Pushing " + str( x.value ) + " to the stack"
stack.push( x )
print "stack after the push..."
stack.print_stack()
root = x
stack.print_stack()
traverse( root );
示例4: _put
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def _put(self, node, key, value, idx):
char = key[idx]
if node is None:
node = Node()
node.char = char
if char < node.char:
node.left = self._put(node.left, key, value, idx)
elif char > node.char:
node.right = self._put(node.right, key, value, idx)
elif idx < len(key) - 1:
node.mid = self._put(node.mid, key, value, idx + 1)
else:
node.value.append(value)
return node
示例5: make_objects
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def make_objects(matrix, row_names):
# Not checking for a square or non-empty matrix but that would be bad.
num_rows = len(matrix)
num_cols = len(matrix[0])
# Dict to keep track of nodes per column to fix left-right links when done.
node_dict = {}
# Header node is a special artificial placeholder in the list of columns.
header = Header(num_cols)
last_col = header
cur_col = last_col
for col_idx in range(num_cols):
cur_col = Column(name=col_idx)
# Populate the nodes in this column.
last_node = cur_col
cur_node = cur_col
for row_idx in range(num_rows):
if matrix[row_idx][col_idx]:
cur_node = Node(column=cur_col, up=last_node,
description=row_names[row_idx])
node_dict[(row_idx, col_idx)] = cur_node
last_node.down = cur_node
last_node = cur_node
cur_col.size += 1
cur_node.down = cur_col
last_col.right = cur_col
cur_col.left = last_col
cur_col.up = last_node
last_col = cur_col
# The very last column loops back to the header.
cur_col.right = header
header.left = cur_col
# Fix left-right links among nodes in each column.
for row_idx in range(num_rows):
initial_node = None
last_node = None
cur_node = initial_node
for col_idx in range(num_cols):
if (row_idx, col_idx) in node_dict:
cur_node = node_dict[(row_idx, col_idx)]
if not initial_node:
initial_node = cur_node
cur_node.left = last_node
if last_node:
last_node.right = cur_node
last_node = cur_node
last_node.right = initial_node
initial_node.left = cur_node
return header
示例6: create_decision_tree_for_k
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def create_decision_tree_for_k(self, pos_data, neg_data, depth, attr, max_depth=None):
'''
Trains and returns a decision tree with the information gain
as the tree splitting criterion. Criterion is a binary function
which checks to see if a word exists in the tweet or not
'''
root = Node(depth=depth)
if self.root is None:
self.root = root
if depth == max_depth:
if len(pos_data) > len(neg_data):
root.label = 1
return root
else:
root.label = -1
return root
if len(pos_data) == 0:
root.label = -1
return root
elif len(neg_data) == 0:
root.label = 1
return root
print 'Current depth: {}'.format(depth)
criterion_word = self.max_gain(pos_data, neg_data)
root.criterion = criterion_word
# cps = set positive tweets that contain the word
# cns = set negative tweets that contain the word
# ncps = set positive tweets that do not contain the word
# ncns = set negative tweets that do not contain the word
cps, ncps, cns, ncns = self.split_on_word(pos_data, neg_data, criterion_word)
if criterion_word == 'rain':
print 'Contains: {}, {}'.format(cps, cns)
print 'Not Contains: {}, {}'.format(ncps, ncns)
root.left = self.create_decision_tree_for_k(ncps, ncns, depth+1, attr, max_depth=max_depth)
root.right = self.create_decision_tree_for_k(cps, cns, depth+1, attr, max_depth=max_depth)
return root
示例7: contains
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
if n1 == n2.left or n1 == n2.right: return n2
if n2 == n1.left or n2 == n1.right: return n2
if (contains(root.left, n1) and contains(root.right, n2)) or\
(contains(root.left, n2) and contains(root.right, n1)):
return root
elif contains(root.left, n1) and contains(root.left,n2):
return fca(root.left,n1,n2)
elif contains(root.right, n1) and contains(root.right,n2):
return fca(root.right,n1,n2)
return None
def contains(root, node):
if not root: return False
if root == node: return True
return contains(root.left, node) or contains(root.right, node)
rt = Node(5)
rt.left = Node(7)
rt.right = Node(10)
rt.left.left = Node(2)
rt.left.right = Node(1)
##print (contains(rt, rt.left))
print (fca(rt, rt.left.left, rt.left.right).val) #7
print (fca(rt, rt.left.left, rt.right).val) #5
print (fca(rt, rt.left.left, rt).val) #5
示例8: build
# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import left [as 别名]
def build(self,node=None,sigMask=None,bkgMask=None):
"""
Builds a decision tree from training data
Recursivly creates a node and then finds the cut which gives the greatest separation
between signal and background. Then applies the cut and creates two daughter nodes
that are then trained on a masked input sample.
"""
# create root node for tree
if node == None:
node = Node()
self.rootNode = node
self.rootNode.root = True
self.rootNode.depth = 0
self.nNodes +=1
# create a mask for the training samples, we will only train on events that
# pass the previous nodes
if sigMask == None :
sigMask = np.ones(self.nSig, dtype=bool)
if bkgMask == None :
bkgMask = np.ones(self.nBkg, dtype=bool)
# check parameters, this may be a leaf...
leafNode = False
if self.nNodes >= self.maxNodes :
leafNode = True
if node.depth >= self.maxDepth :
leafNode = True
sigEvents = long(np.sum(sigMask))
bkgEvents = long(np.sum(bkgMask))
if sigEvents + bkgEvents < 2*self.nEventsMin:
leafNode = True
if sigEvents<=0 or bkgEvents<=0:
leafNode = True
# if this is a leaf node, set the return value for the node and then return
if leafNode :
node.leaf = True
if float(sigEvents)/(sigEvents+bkgEvents) > 0.5:
node.retVal = 1
else :
node.retVal = -1
return
# Scan over each cut value of each variable to find cut which offers the best separation
bestGini=-1.
bestVar = -1
bestCutVal = -1.
parentIndex = weightedGini(sigEvents,bkgEvents)
for var in xrange(self.nVars) :
# use numpy histogram fn to find best cut value
histRange = (
min(self.bkgData[bkgMask,var].min(),self.sigData[sigMask,var].min()),
max(self.bkgData[bkgMask,var].max(),self.sigData[sigMask,var].max())
)
bkgHist, bins = np.histogram(self.bkgData[bkgMask,var],self.nCuts,
range=histRange,weights=self.bkgWeights[bkgMask])
bkgYield = np.cumsum(bkgHist, dtype=float)
sigHist, bins = np.histogram(self.sigData[sigMask,var],bins,weights=self.sigWeights[sigMask])
sigYield = np.cumsum(sigHist, dtype=float)
# calculate the increase in the separation index between the parent node the daughter nodes
leftIndex = vecWeightedGini(sigYield,bkgYield)
rightIndex = vecWeightedGini(sigEvents-sigYield,bkgEvents-bkgYield)
diff = (parentIndex - leftIndex - rightIndex)/(sigEvents+bkgEvents)
maxInd = diff[:-1].argmax()
if diff[maxInd] >= bestGini :
bestGini = diff[maxInd]
bestVar = var
bestCutVal = bins[maxInd+1]
# apply cut values to node
node.setCuts(bestVar,bestCutVal)
# create two daughter nodes
self.nNodes+=2
leftnode = Node()
leftnode.parent = node
node.left = leftnode
node.left.depth = node.depth+1
rightnode = Node()
rightnode.parent = node
node.right = rightnode
node.right.depth = node.depth+1
# copy the masks and update them with the results of the node
sigMaskLeft = np.copy(sigMask)
sigMaskRight = np.copy(sigMask)
for i in xrange(self.nSig):
if sigMask[i] :
#.........这里部分代码省略.........