当前位置: 首页>>代码示例>>Python>>正文


Python Node.right方法代码示例

本文整理汇总了Python中node.Node.right方法的典型用法代码示例。如果您正苦于以下问题:Python Node.right方法的具体用法?Python Node.right怎么用?Python Node.right使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在node.Node的用法示例。


在下文中一共展示了Node.right方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: make_tree

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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
开发者ID:jhlusko,项目名称:schoolwork,代码行数:55,代码来源:e3a.py

示例2: arraytoBST

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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
开发者ID:kendricktang,项目名称:python_problems,代码行数:12,代码来源:xtoBST.py

示例3: main

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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 );
开发者ID:Ross-Marshall,项目名称:Algorithms-Robert-Sedgewick,代码行数:42,代码来源:parse_tree.py

示例4: _put

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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
开发者ID:guolas,项目名称:boggle,代码行数:16,代码来源:trie.py

示例5: create_decision_tree_for_k

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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
开发者ID:taehoonl,项目名称:HashtagWeather,代码行数:46,代码来源:dtree.py

示例6: contains

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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

开发者ID:paulan94,项目名称:CTCIPaul,代码行数:31,代码来源:fca_code.py

示例7: build

# 需要导入模块: from node import Node [as 别名]
# 或者: from node.Node import right [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] :
#.........这里部分代码省略.........
开发者ID:martynjarvis,项目名称:bdt-thing,代码行数:103,代码来源:tree.py


注:本文中的node.Node.right方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。