• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tree.Tree类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tree.Tree的典型用法代码示例。如果您正苦于以下问题:Python Tree类的具体用法?Python Tree怎么用?Python Tree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: BuildTree

def BuildTree(path_tuple):
    """
    Build a tree structure from a given path tuple
    """
    if _debug: print "##\nBuild Tree...\ntuple:", path_tuple
    
    node_to_split,y_value = FindBestGain(path_tuple)
    
    if node_to_split < 0:
        if _debug: print "found leaf for tuple: ", path_tuple
        training_tree = Tree("leaf")
        training_tree.y_value = y_value
        training_tree.is_leaf = True
    else:
        # Create node for attribute to split on
        training_tree = Tree(_attrib_dict[str(node_to_split)])
        
        # Build left side of tree for node
        left_tuple = path_tuple + [(node_to_split,0)]
        left_tree = BuildTree(left_tuple)
        training_tree.AddLeftChild(left_tree)
            
        # Build right side of tree for node
        right_tuple = path_tuple + [(node_to_split, 1)]
        right_tree = BuildTree(right_tuple)
        training_tree.AddRightChild(right_tree)

    return training_tree
开发者ID:jwei7er,项目名称:machine_learning,代码行数:28,代码来源:id3.py


示例2: test_traverse_returns_none_when_operation_always_returns_false

def test_traverse_returns_none_when_operation_always_returns_false():
    t = Tree("a")
    t.add_child("b")

    node = t.traverse(lambda n: False)

    assert_that(node, is_(None))
开发者ID:povilasb,项目名称:pytree,代码行数:7,代码来源:test_tree.py


示例3: read_tree

 def read_tree(self, line):
     parents = map(int,line.split())
     trees = dict()
     root = None
     for i in xrange(1,len(parents)+1):
         #if not trees[i-1] and parents[i-1]!=-1:
         if i-1 not in trees.keys() and parents[i-1]!=-1:
             idx = i
             prev = None
             while True:
                 parent = parents[idx-1]
                 if parent == -1:
                     break
                 tree = Tree()
                 if prev is not None:
                     tree.add_child(prev)
                 trees[idx-1] = tree
                 tree.idx = idx-1
                 #if trees[parent-1] is not None:
                 if parent-1 in trees.keys():
                     trees[parent-1].add_child(tree)
                     break
                 elif parent==0:
                     root = tree
                     break
                 else:
                     prev = tree
                     idx = parent
     return root
开发者ID:Jarvx,项目名称:web-classification,代码行数:29,代码来源:dataset.py


示例4: fitness_eval

    def fitness_eval(self, pacman, ghost):
        # Create three identical ghosts
        ghost.board = self.board
        pacman.board = self.board
        ghost.score = 0
        pacman.score = 0
        ghosts = [copy.deepcopy(ghost) for i in range(3)]

        self.init_log(pacman, ghosts)

        # Run turns until the game is over
        while not self.game_over and self.time > 0 and len(self.board.pills) > 0:
            self.turn(pacman, ghosts)
            self.time -= 1
            if len(self.board.pills) == 0:
                pacman.score += int(self.time/float(self.tot_time) * 100)
            self.log_turn(pacman, ghosts)

        pacman.score = max(pacman.score, 1)

        ghost.score = -pacman.score
        ghost.score -= self.parsimony_coef_ghost*Tree.find_depth(ghost.tree)

        # Parsimony pressure
        pacman.score -= self.parsimony_coef_pacman*Tree.find_depth(pacman.tree)
        pacman.score = max(pacman.score, 1)

        return pacman.score
开发者ID:matthewia94,项目名称:cs5401,代码行数:28,代码来源:pacman.py


示例5: make_master_tree

        def make_master_tree(
            n,
            method,
            names=None,
            inner_edge_params=(1, 1),
            leaf_params=(1, 1),
            distribution_func=np.random.gamma,
            ):
            """
            Function returns a tree object with n tips,
            named according to `names`, and constructed
            according to `method`, which is one of 'random_topology',
            'random_yule' and 'random_coal'
            """

            if method == 'random_topology':
                master_topology = Tree.new_random_topology(n,
                        names=names, rooted=True)
                master_tree = \
                    master_topology.randomise_branch_lengths(inner_edges=inner_edge_params,
                        leaves=leaf_params,
                        distribution_func=branch_length_func)
                master_tree.newick = '[&R] ' + master_tree.newick
            elif method == 'random_yule':
                master_tree = Tree.new_random_yule(n, names=names)
            elif method == 'random_coal':
                master_tree = Tree.new_random_coal(n, names=names)
            return master_tree
开发者ID:kgori,项目名称:clustering_project,代码行数:28,代码来源:seqsim.py


示例6: main

def main():
	bordVariables = bord(2) # return [carsList,width,exit]
	global WIDTH; WIDTH = bordVariables[1]
	global CARS_LIST; CARS_LIST = bordVariables[0]
	global INITIAL_STATE; INITIAL_STATE = CARS_LIST.getFirstState()
	global STATES_ARCHIVE; STATES_ARCHIVE = Tree(WIDTH, CARS_LIST.getDirectionsList())

	aantalCars = len(CARS_LIST.cars)
	# voeg vaak een state toe aan de tree
	for i in range(0, 100000):
		randomState = []
		for j in range(0, aantalCars):
			randomState.append(randint(0,WIDTH-2)*WIDTH + randint(0,WIDTH - 2))

		# print randomState

		STATES_ARCHIVE.addState(randomState, INITIAL_STATE)
	print "ik ben klaar met states toevoegen"
	
	# # zoek een state in de tree
	# for i in range(0, 100000):
	# 	randomState = []
	# 	for j in range(0, aantalCars):
	# 		randomState.append(randint(0,WIDTH-2)*WIDTH + randint(0,WIDTH - 2))
	# 	STATES_ARCHIVE.checkState(randomState)
	# print "klaar met states checken"



	STATES_ARCHIVE.addState(INITIAL_STATE, INITIAL_STATE)
开发者ID:A-meerdervan,项目名称:RushHourGit,代码行数:30,代码来源:TestTree.py


示例7: main

def main():

	# Car1 = Car(22, False, 3)
	# Car2 = Car(9, False, 2)
	# Car3 = Car(10, True, 2)
	# RedCar = Car(20, True, 2)

	# CARS_LIST.cars.append(Car1)
	# CARS_LIST.cars.append(Car2)
	# CARS_LIST.cars.append(Car3)
	# CARS_LIST.cars.append(RedCar)

	RedCar = Car(20, True, 2)
	Car1 = Car(0, False, 2)
	Car2 = Car(12, True, 2)
	Car3 = Car(3, False, 2)
	Car4 = Car(4, True, 2)
	Car5 = Car(10, True, 2)
	Car6 = Car(14, True, 2)
	Car7 = Car(16, False, 2)
	Car8 = Car(17, False, 3)
	Car9 = Car(25, True, 2)
	Car10 = Car(27, True, 2)
	Car11 = Car(32, True, 2)
	Car12 = Car(34, True, 2)

	CARS_LIST.cars.append(Car1)
	CARS_LIST.cars.append(Car2)
	CARS_LIST.cars.append(Car3)
	CARS_LIST.cars.append(Car4)
	CARS_LIST.cars.append(Car5)
	CARS_LIST.cars.append(Car6)
	CARS_LIST.cars.append(Car7)
	CARS_LIST.cars.append(Car8)
	CARS_LIST.cars.append(Car9)
	CARS_LIST.cars.append(Car10)
	CARS_LIST.cars.append(Car11)
	CARS_LIST.cars.append(Car12)
	CARS_LIST.cars.append(RedCar)

	# TEST dept first algorithme:
	global INITIAL_STATE; INITIAL_STATE = CARS_LIST.getFirstState()
	global STATES_ARCHIVE; STATES_ARCHIVE = Tree(WIDTH, CARS_LIST.getDirectionsList())
	algorithm(INITIAL_STATE)
	path1 = SOLUTION_PATHS[0]

	# print results
	# print "length solutions ", len(SOLUTIONS)
	#rint SOLUTIONS
	print len(SOLUTION_PATHS)
	listSolutionsPaths = []
	for sols in SOLUTION_PATHS:
		listSolutionsPaths.append(len(sols))
	print listSolutionsPaths

	pathDepth = []
	for state in path1[:-1]:
		print len(state), state
		pathDepth.append(STATES_ARCHIVE.goToEndNode(state).depth)
	print pathDepth
开发者ID:A-meerdervan,项目名称:RushHourGit,代码行数:60,代码来源:DeptFirst2.py


示例8: main

def main():
    tree = Tree('pie')
    tree.add_item('cake')
    tree.add_item('cookie')
    for item in tree:
        print('{}: {}'.format(item.datum, item.height()))
    #Should print:
    #cake: 0
    #pie: 1
    #cookie: 0

    tree.add_item('cupcake')
    for item in tree:
        print('{}: {}'.format(item.datum, item.height()))
    #Should print:
    #cupcake: 0
    #cake: 1
    #pie: 2
    #cookie: 0

    #this constructs the tree shown in the exercise
    other_tree = Tree(1)
    for i in [2, 3, 4, 6, 5, 7]:
        other_tree.add_item(i)
    print(list(map(lambda d: d.datum, other_tree)))
开发者ID:AdmiralAckbar13,项目名称:nmt_python_labs,代码行数:25,代码来源:tree_test.py


示例9: get_best_TC_tree

def get_best_TC_tree(
    dv_file,
    gm_file,
    label_file,
    tree_files,
    name='unnamed_tree',
    ):
    """
    Given a distance-variance file, a genome-map file, a label file
    and a number of tree files
    """

    if not isinstance(tree_files, list):
        return Tree.new_treecollection_tree(dv_file, gm_file,
                label_file, tree_files, name)
    best_score = float('inf')
    best_tree = None
    starts = len(tree_files)

    for i in range(starts):
        guide = tree_files[i]
        current_tree = Tree.new_treecollection_tree(dv_file, gm_file,
                label_file, guide, name)
        if current_tree.score < best_score:
            best_score = current_tree.score
            best_tree = current_tree

    return best_tree
开发者ID:kgori,项目名称:clustering_project,代码行数:28,代码来源:cluster_TC_input.py


示例10: main

def main():

    init_population = generate_init_population()
    result = False
    counter = 0

    while counter < ITERATIONS_COUNT:
        print("************************************************************************************************************"
              "************************************************************************************************************")
        print(counter)
        best_individuals = deepcopy(reproduce(init_population))

        if len(best_individuals) == 0:
            print("Reproduction empty")
            break

        new_generation = deepcopy(create_new_generation(best_individuals))
        mutated_trees = deepcopy(mutate_trees(new_generation))
        check_fitness(mutated_trees)
        init_population = deepcopy(mutated_trees)

        if len(init_population) == 0:
            print("Empty population")
            break
        counter += 1

    print("End")
    if len(results) > 0:
        print("")
        print "MIN RESULT"
        print Tree.tree_map_to_string(min(results))
        print min(results).init_tree
        print min(results).fitness
开发者ID:Mirann,项目名称:Genetic,代码行数:33,代码来源:__init__.py


示例11: test_new_tree_add_2_nodes_and_print_it

 def test_new_tree_add_2_nodes_and_print_it(self):
     t = Tree()
     n = Node(title='test', id='1', parent_id='root')
     t.add(n)
     n = Node(title='test2', id='2', parent_id='1')
     t.add(n)
     print(t)
开发者ID:mkgilbert,项目名称:GDriveMgr,代码行数:7,代码来源:test_tree.py


示例12: testTraverse

    def testTraverse(self):
        tree = Tree()
        for word in insert_queue:
            tree.insert(word)

        insert_queue.sort()
        self.assertEqual(tree.inorder_traverse(), " ".join(insert_queue))
开发者ID:theevocater,项目名称:pydatastructures,代码行数:7,代码来源:test.py


示例13: check_fitness

def check_fitness(trees):
    errors = []
    for one_tree in trees:
        if len(one_tree.tree_map) == 0:
            continue
        sum_error = 0
        good_individual = True
        for i in range(0, len(VARIABLE_VALUES_SET)):
            error = Reproductor.get_error(one_tree, TARGET_VALUES[i], VARIABLE_VALUES_SET[i])
            if error > ALLOWABLE_ERROR:
                good_individual = False
            sum_error += error
        if isinf(sum_error):
            continue
        errors.append(sum_error)
        if good_individual or sum_error < TARGET_RESULT:
            print("RESULT")
            print(Tree.tree_map_to_string(one_tree.tree_map))
            print(one_tree.init_tree)
            one_tree.fitness = sum_error
            results.append(one_tree)
    print("MIN FITNESS RESULT: ", min(errors))
    print "AVERAGE FITNESS: ", sum(errors)/len(errors)
    print "length ", len(errors)
    print "results "
    for r in results:
        print "fitness ", r.fitness
        print Tree.tree_map_to_string(r.tree_map)
开发者ID:Mirann,项目名称:Genetic,代码行数:28,代码来源:__init__.py


示例14: main

def main():
    a = Tree(1)
    b = Tree(4)
    c = Tree(6)
    d = Tree(8)
    e = Tree(2, a)
    f = Tree(3, e, b)
    g = Tree(7, c, d)
    h = Tree(5, f, g)

    print "####### Left View ########"
    print_next = False
    for node in Tree.get_level_order_traversal(h):
        if not isinstance(node, Tree):
            print_next = True
        elif print_next:
            print node.v
            print_next = False
            
    print "####### Right View ########"
    prev = None
    for node in Tree.get_level_order_traversal(h):
        if not isinstance(node, Tree) and prev:
            print prev.v
        prev = node
    print node.v
开发者ID:azhar3339,项目名称:algorithms,代码行数:26,代码来源:views_of_tree.py


示例15: getObjectsTree

def getObjectsTree(qTreeView, table, indexes, extract):
    """Create an object tree representation from QTreeView.
    """
    tree = Tree()
    model = qTreeView.model()
    extracted = tree.fromQStandardItemModel(model, table, indexes, extract)
    return tree, extracted
开发者ID:smajida,项目名称:detection,代码行数:7,代码来源:common.py


示例16: testProperty

    def testProperty(self):

        x = Tree(value=None)
        self.assertTrue(x.value == None)

        x.value = 5
        self.assertTrue(x.value == 5)
开发者ID:rcludwick,项目名称:TreePy,代码行数:7,代码来源:test.py


示例17: filelists_from_spec

def filelists_from_spec(spec, specpath):
    res = Tree()
    for pkg in spec.packages:
        name = "%s.install.in" % mappkgname.map_package_name(pkg.header)
        res.append("debian/%s" % name, 
                   files_from_pkg(spec.sourceHeader['name'], pkg, specpath))
    return res
开发者ID:BATYD-Turksat,项目名称:xenserver-core,代码行数:7,代码来源:debianmisc.py


示例18: eval_decmodel

def eval_decmodel(s):
    d = eval(s)
    v = d["lagrange_version"] 
    if v != VERSION:
        print >> sys.stderr, "***Version mismatch: %s (expecting %s)***" \
              % (v, VERSION)
        print >> sys.stderr, "Things may not work as expected"
    for x in ("area_labels", "taxon_range_data", "newick_trees"):
        assert x in d, "required for analysis, but missing: %s" % x
    labels = d["area_labels"]
    nareas = len(labels)
    data = d["taxon_range_data"]
    maxareas = d.get("max_range_size") or len(labels)
    dists = d["ranges"]
    excluded = d["excluded_ranges"]
    dm = d["area_dispersal"]
    periods = d["dispersal_durations"]
    model = DECModel(nareas, labels, periods=periods, dists=dists)
    model.Dmask[:] = dm
    trees = d["newick_trees"]
    newicktree = trees[0]["newick"]
    nodelabels = trees[0]["included"]
    root_age = trees[0]["root_age"] or None
    tree = Tree(newicktree, periods=periods, root_age=root_age)
    tree.set_default_model(model)
    tree.set_tip_conditionals(data)
    base_rates = d["base_rates"]
    if base_rates == "__estimate__":
        pass
    else:
        base_rates = (d["base_rates"]["dispersal"], d["base_rates"]["extinction"])
    return model, tree, data, nodelabels, base_rates
开发者ID:rhr,项目名称:lagrange-configurator,代码行数:32,代码来源:input.py


示例19: testIsRoot

 def testIsRoot(self):
   if IGNORE_TEST:
     return
   self.assertTrue(self.root.isRoot())
   new_tree = Tree("DUMMY_TREE")
   self.root.addChild(new_tree)
   self.assertFalse(new_tree.isRoot())
   self.assertTrue(self.root.isRoot())
开发者ID:ScienceStacks,项目名称:SciSheets,代码行数:8,代码来源:test_tree.py


示例20: test_add_child_appends_node_to_the_child_list

def test_add_child_appends_node_to_the_child_list():
    t = Tree("a")
    t.add_child("b")

    t.add_child("c")

    assert_that(t.children[0].value, is_("b"))
    assert_that(t.children[1].value, is_("c"))
开发者ID:povilasb,项目名称:pytree,代码行数:8,代码来源:test_tree.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python nodes.check_serialization函数代码示例发布时间:2022-05-27
下一篇:
Python tree.Node类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap