def main(): tree = Tree() #set root node root = "Forest" mode = input( 'ENTER 0 FOR DFS, ENTER 1 FOR BFS\nNOTE: Strings must be between quotes\n' ) #print(mode) #print(mode == 1) #add elements to the graph #USAGE: tree.add_node(leaf,parent) tree.add_node(root) tree.add_node("Steve", root) tree.add_node("Kao", root) tree.add_node("Diplo", root) tree.add_node("Lol", "Steve") tree.add_node("Amy", "Steve") tree.add_node("Julio", "Amy") tree.add_node("Mary", "Amy") tree.add_node("Mark", "Julio") tree.add_node("Jane", "Mark") tree.add_node("Tahir", "Kao") tree.add_node("What", "Tahir") tree.display(root) if (mode == 0): print("DEPTH-FIRST ITERATION:\n") for node in tree.traverse(root): tree.specialdisplay(root, node) print("\n") time.sleep(1) if (mode == 1): print("BREADTH-FIRST ITERATION:\n") for node in tree.traverse(root, mode=BREADTH): tree.specialdisplay(root, node) print("\n") time.sleep(1) restart = input('RESTART? ("y" or "n")\n') if (restart == 'y' or restart == 'Y'): main()
__author__ = 'Suraj' from tree import Tree tree = Tree() tree.display() tree.userTurn() tree.display()
def importData(fname, displayTree=False, colSep=',', headerLine=False, verbose=False): """ Import tree data from a CSV (text) file or list. The data should be in the following format: node_ID_number,node_parent_ID_number,data_item1,data_item2,...,data_itemN\n The separator can, optionally, be a character other than "," The root node must have a parent id of 0 and normally should also have an index of 1 From MATLAB one can produce tree structures and dump data in the correct format using https://github.com/raacampbell13/matlab-tree and the tree.dumptree method Inputs: fname - if a string, importData assumes it is a file name and tries to load the tree from file. if it is a list, importData assumes that each line is a CSV data line and tries to convert to a tree. displayTree - if True the tree is printed to standard output after creation colSep - the data separator, a comma by default. headerLine - if True, the first line is stripped off and considered to be the column headings. headerLine can also be a CSV string or a list that defines the column headings. Must have the same number of columns as the rest of the file. verbose - prints diagnositic info to screen if true """ if verbose: print("tree.importData importing file %s" % fname) #Error check if isinstance(fname, str): if os.path.exists(fname) == False: print("Can not find file " + fname) return #Read in data fid = open(fname, 'r') contents = fid.read().split('\n') fid.close() elif isinstance(fname, list): contents = fname #assume that fname is data rather than a file name #Get header data if present if headerLine == True: header = contents.pop(0) header = header.rstrip('\n').split(colSep) elif isinstance(headerLine, str): header = headerLine.rstrip('\n').split(colSep) elif isinstance(headerLine, list): header = headerLine else: header = False data = [] for line in contents: if len(line) == 0: continue dataLine = line.split(colSep) if len(header) != len(dataLine): print( "\nTree file appears corrupt! header length is %d but data line length is %d.\ntree.importData is aborting.\n" % (len(header), len(dataLine))) return False theseData = list( map(int, dataLine[0:2])) #add index and parent to the first two columns #Add data to the third column. Either as a list or as a dictionary (if header names were provided) if header != False: #add as dictionary dataCol = dict() for ii in range(len(header) - 2): ii += 2 dataCol[header[ii]] = dataTypeFromString.convertString( dataLine[ii]) else: dataCol = dataLine[2:] #add as list of strings theseData.append(dataCol) data.append(theseData) if verbose: print("tree.importData read %d rows of data from %s" % (len(data), fname)) #Build tree tree = Tree() tree.add_node(0) for thisNode in data: tree.add_node(thisNode[0], thisNode[1]) tree[thisNode[0]].data = thisNode[2] #Optionally dump the tree to screen (unlikely to be useful for large trees) if displayTree: tree.display(0) for nodeID in tree.traverse(0): print("%s - %s" % (nodeID, tree[nodeID].data)) return tree
#Add some data to the vertebrates treeOfLife["Vertebrates"].data = 'they have backbones' treeOfLife["Fish"].data = 'they swim' treeOfLife["Amphibians"].data = 'they croak' treeOfLife["Reptiles"].data = 'they stick to walls' treeOfLife["Mammals"].data = 'they have udders' print("List of nodes:") print(list(treeOfLife.nodes.keys())) print("") print("Children of node 'Vertebrates'") print(treeOfLife.nodes['Vertebrates'].children) print("") print(treeOfLife.display('Life')) print("\n***** Depth-first *****") for nodeID in treeOfLife.traverse("Life"): print(nodeID) print("\n***** Width-first *****") for nodeID in treeOfLife.traverse("Life", mode=_WIDTH): print(nodeID) print("\n***** Width-first of all data in vertebrates *****") for nodeID in treeOfLife.traverse("Vertebrates", mode=_WIDTH): print("%s - %s" % (nodeID, treeOfLife[nodeID].data)) print("\nLeaves:") print(treeOfLife.findLeaves('Life'))
def test_node(): def test_preorder_iterator(): tree = Tree('src_ip dst_ip') create_node(2,1,tree) create_node(2,2,tree) create_node(1,2,tree) create_node(3,1,tree) create_node(4,1,tree) print tree.get_root.preorder() return tree def create_node_prefix(src,dst,src_size,dst_size,tree): key = {} a = IPv4Address(src,src_size) b = IPv4Address(dst,dst_size) key["src_ip"] = a key["dst_ip"] = b node1 = NumericalValueNode(key,10,None,tree) return node1 def create_detached_node(src,dst,tree): key = {} a = IPv4Address(src,32) b = IPv4Address(dst,32) key["src_ip"] = a key["dst_ip"] = b node1 = NumericalValueNode(key,10,None,tree) return node1 def create_node(src,dst,tree): key = {} a = IPv4Address(src,32) b = IPv4Address(dst,32) key["src_ip"] = a key["dst_ip"] = b node1 = NumericalValueNode(key,10,None,tree) node1.integrate_node() return node1 def check_tree(tree): nodePP = create_node_prefix("0.0.0.0","0.0.0.0",0,0,tree) nodeCH = create_node_prefix("108.64.64.0","108.96.64.0",19,19,tree) nodeJL = create_node_prefix("108.64.88.0","108.96.77.88",24,31,tree) if tree.get_root().equivalent(nodePP,tree.get_dim()): print "test tree root success" else: print "test tree root ERROR" return False listNone = [] try: listNone.append(tree.get_root().get_children()['src_ip'][0]['dst_ip'][1]) except KeyError: listNone.append(None) try: listNone.append(tree.get_root().get_children()['src_ip'][1]['dst_ip'][0]) except KeyError: listNone.append(None) ch = tree.get_root().get_children()['src_ip'][0]['dst_ip'][0] mn = tree.get_root().get_children()['src_ip'][1]['dst_ip'][1] af = ch.get_children()['src_ip'][0]['dst_ip'][0] ag = ch.get_children()['src_ip'][0]['dst_ip'][1] jl = ch.get_children()['src_ip'][1]['dst_ip'][0] bg = ch.get_children()['src_ip'][1]['dst_ip'][1] bf = jl.get_children()['src_ip'][0]['dst_ip'][0] i_f = jl.get_children()['src_ip'][1]['dst_ip'][0] try: listNone.append(jl.get_children()['src_ip'][0]['dst_ip'][1]) except KeyError: listNone.append(None) try: listNone.append(jl.get_children()['src_ip'][1]['dst_ip'][1]) except KeyError: listNone.append(None) ok = True for e in listNone: if e!=None: ok = False if ok: print "test tree empty_node success" else: print "test tree empty_node ERROR" return False nodeAF = create_detached_node("108.64.77.102","108.96.77.88",tree) nodeBG = create_detached_node("108.64.88.102","108.96.88.88",tree) nodeAG = create_detached_node("108.64.77.102","108.96.88.88",tree) nodeBF = create_detached_node("108.64.88.102","108.96.77.88",tree) nodeIF = create_detached_node("108.64.88.130","108.96.77.88",tree) nodeMN = create_detached_node("202.102.10.10","210.110.0.0",tree) ok = True if not nodeAF.equivalent(af,tree.get_dim()): ok = False if not nodeAG.equivalent(ag,tree.get_dim()): ok = False if not nodeBF.equivalent(bf,tree.get_dim()): ok = False if not nodeIF.equivalent(i_f,tree.get_dim()): ok = False if not nodeMN.equivalent(mn,tree.get_dim()): ok = False if not nodeBG.equivalent(bg,tree.get_dim()): ok = False if ok: print "test tree leaf nodes success" else: print "test tree leaf ERROR" return False ok = True if not nodeCH.equivalent(ch,tree.get_dim()): ok = False if not nodeJL.equivalent(jl,tree.get_dim()): ok = False if ok: print "test tree internal nodes success" else: print "test tree internal nodes ERROR" return False ok = True if not (tree.get_root().get_value() == 0 and ch.get_value() == 0 and jl.get_value() == 0): ok = False if not (mn.get_value() == 10 and af.get_value() == 10 and ag.get_value() == 20 and bg.get_value() == 10\ and i_f.get_value() == 10 and bf.get_value() == 10): ok = False if ok: print "test tree value success" else: print "test tree value nodes ERROR" return False return True def generate_posssibilities(p,E): if p==1: return [[x] for x in E] #cas ou p=1 else: R=[] for x in E: F=E[:] # recopier E F.remove(x) # enlever x PGI=generate_posssibilities(p-1,F) # appel recursif Cx=PGI[:] # recopie du resultat for A in Cx: A.append(x)# recombiner avec x tous les elements R+=Cx # Ajouter les resultats obtenus return R key = {} a = IPv4Address("108.64.77.102",32) b = IPv4Address("108.96.77.88",32) key["src_ip"] = a key["dst_ip"] = b node1 = NumericalValueNode(key,10,[]) key = {} c = IPv4Address("108.64.88.102",32) d = IPv4Address("108.96.88.88",32) key["src_ip"] = c key["dst_ip"] = d node2 = NumericalValueNode(key,20,[]) dict_dim={"src_ip":"ip_addr","dst_ip":"ip_addr"} common_prefix={"src_ip":a.common_prefix(c),"dst_ip":b.common_prefix(d)} dim = ["src_ip","dst_ip"] child = Node.create_children_tree(dim,common_prefix,node1,node2,[node1,node2]) if IPv4Address.IntToDottedIP(common_prefix["src_ip"].get_prefix()) == "108.64.64.0" and common_prefix["src_ip"].get_prefix_len() == 19 and IPv4Address.IntToDottedIP(common_prefix["dst_ip"].get_prefix()) == "108.96.64.0" and common_prefix["dst_ip"].get_prefix_len() == 19: print "test nodes common_prefix success" else: print "test nodes common_prefix ERROR" if child['src_ip'][0]['dst_ip'][0] == node1 and not 1 in child['src_ip'][0]['dst_ip'].keys() and not 0 in child['src_ip'][1]['dst_ip'].keys() and child['src_ip'][1]['dst_ip'][1] == node2: print "test nodes create_children success" else: print "test nodes create_children ERROR" key = {} c = IPv4Address("108.64.77.102",32) d = IPv4Address("108.96.88.88",32) key["src_ip"] = c key["dst_ip"] = d tt = node1.__class__.__name__ node2 = globals()[tt](key,20,[]) common_prefix={"src_ip":a.common_prefix(c),"dst_ip":b.common_prefix(d)} dim = ["src_ip","dst_ip"] child = Node.create_children_tree(dim,common_prefix,node1,node2,[node1,node2]) if IPv4Address.IntToDottedIP(common_prefix["src_ip"].get_prefix()) == "108.64.77.102" and common_prefix["src_ip"].get_prefix_len() == 31 and IPv4Address.IntToDottedIP(common_prefix["dst_ip"].get_prefix()) == "108.96.64.0" and common_prefix["dst_ip"].get_prefix_len() == 19: print "test nodes common_prefix with artificial split success" else: print "test nodes common_prefix ERROR" #if child['src_ip'][0]['dst_ip'][0] == node1 and not 1 in child['src_ip'].keys() and child['src_ip'][0]['dst_ip'][1] == node2: # print "test nodes create_children 2 success" #else: # print "test nodes create_children 2 ERROR" tree = Tree(dim) if tree.is_empty() == True: print "test tree is_empty 1 success" else: print "test tree is_empty 1 ERROR" nodeAF = create_node("108.64.77.102","108.96.77.88",tree) key = {} if tree.is_empty() == False: print "test tree is_empty 2 success" else: print "test tree is_empty 2 ERROR" node2 = create_node("108.64.77.102","108.96.77.88",tree) tree = Tree(dim) nodeBG = create_node("108.64.88.102","108.96.88.88",tree) nodeAF = create_node("108.64.77.102","108.96.77.88",tree) nodeAG = create_node("108.64.77.102","108.96.88.88",tree) nodeAG2 = create_node("108.64.77.102","108.96.88.88",tree) nodeBF = create_node("108.64.88.102","108.96.77.88",tree) nodeIF = create_node("108.64.88.130","108.96.77.88",tree) """ explore = tree.get_root().explore_intern(dim,dict_dim,IPv4Address(32,"108.64.88.130")) print explore[0] print explore[1] """ nodeMN = create_node("202.102.10.10","210.110.0.0",tree) print tree.display() check_tree(tree) tree = Tree(dim) nodeAF = create_node("108.64.77.102","108.96.77.88",tree) nodeBG = create_node("108.64.88.102","108.96.88.88",tree) nodeAG = create_node("108.64.77.102","108.96.88.88",tree) nodeBF = create_node("108.64.88.102","108.96.77.88",tree) nodeIF = create_node("108.64.88.130","108.96.77.88",tree) nodeMN = create_node("202.102.10.10","210.110.0.0",tree) nodeAG.get_parent().remove_children(nodeAG) if not 1 in nodeAG.get_parent().get_children()['src_ip'][0]['dst_ip'].keys() and nodeAG.get_parent().get_value() == 10: print "Test tree remove success" else: print "Test tree remove ERROR" print tree.get_root.preorder() print tree.display()
tree[parent] except KeyError: tree.add_node(parent) try: tree[child] except KeyError: tree.add_node(child) tree[parent].add_child(child) tree[child].add_parent(parent) query = ("SELECT id, name FROM imm_web") cursor.execute(query) id_name_dict = {} for (id, name) in cursor: id_name_dict[id] = name tree.display(1) return_info = dict() print("***** DEPTH-FIRST ITERATION *****") for node in tree.traverse(1): print(str(node) + ", " + id_name_dict[node] + ", " + str(tree[node].parent)) return_info[node] = [id_name_dict[node], tree[node].parent] print("***** BREADTH-FIRST ITERATION *****") for node in tree.traverse(1, mode=_BREADTH): print(str(node) + ", " + id_name_dict[node]) cursor.close() cnx.close()
#for i in range(0, len(path_cond_state)): # constrain = constrain + " && " + path_cond_state[i] #path_cond.append(constrain) #print ("path_cond: ", path_cond) if branch_boundrary > 0: for i in range(0, 1): counter = 0 for j in range(branch_boundrary, len(info)): temp = branch_leaf[i] if counter == 0: tree.add_node(info[j], info[temp]) else: tree.add_node(info[j], info[j - 1]) counter += 1 tree.display(info[0]) #print("***** DEPTH-FIRST ITERATION *****"), '\n' #print ("region2:\n") for node in tree.traverse(info[0]): if "region" not in node: dfs.append(node) for i in range(0, len(dfs)): region_path.write(dfs[i]) region_path.close() """ #print (dfs) for i in range(0, len(p_num)-1): #if (p_num[i+1] < p_num[i]) and ("}" in dfs[i+1]): if (p_num[i+1] < p_num[i]) and ("{" not in dfs[i+1]): p_num.insert(i+1, 99)
if __name__ == "__main__": from running_vms import running_vms from running_groups import running_groups from vm_snaps import vm_snaps from tree import Tree rgs = running_groups() rg = rgs.pop() snaps_tree = Tree() snaps_tree.add_node(rg, None) for vm in running_vms(): vm_snaps(vm, snaps_tree, rg) snaps_tree.display(rg)
from tree import Tree tree = Tree() tree.add_node(1) # root node tree.add_node(2,3) # root node tree.add_node(4,5) # root node tree.add_node(6,7) # root node tree.display(1)
# Copyright (C) by Brett Kromkamp 2011-2014 ([email protected]) # You Programming (http://www.youprogramming.com) # May 03, 2014 from tree import Tree (_ROOT, _DEPTH, _BREADTH) = range(3) tree = Tree() tree.add_node("Harry") # root node tree.add_node("Jane", "Harry") tree.add_node("Bill", "Harry") tree.add_node("Joe", "Jane") tree.add_node("Diane", "Jane") tree.add_node("George", "Diane") tree.add_node("Mary", "Diane") tree.add_node("Jill", "George") tree.add_node("Carol", "Jill") tree.add_node("Grace", "Bill") tree.add_node("Mark", "Jane") tree.display("Harry") print("***** DEPTH-FIRST ITERATION *****") for node in tree.traverse("Harry"): print(node) print("***** BREADTH-FIRST ITERATION *****") for node in tree.traverse("Harry", mode=_BREADTH): print(node)
from node import Node from tree import Tree from random import randrange if __name__ == "__main__": arr = [randrange(1,100) for i in range(100)] #[print(i) for i in arr] tree = Tree(verbose=False) [tree.addNode(i) for i in arr] print("tree height: ", tree.getHeight()) tree.display() tree.getInOrder() tree.getPreOrder() tree.findValue(10)
def importData(fname, displayTree=False, colSep=',', headerLine=False, verbose=False): """ Import tree data from a CSV (text) file or list. The data should be in the following format: node_ID_number,node_parent_ID_number,data_item1,data_item2,...,data_itemN\n The separator can, optionally, be a character other than "," The root node must have a parent id of 0 and normally should also have an index of 1 From MATLAB one can produce tree structures and dump data in the correct format using https://github.com/raacampbell13/matlab-tree and the tree.dumptree method Inputs: fname - if a string, importData assumes it is a file name and tries to load the tree from file. if it is a list, importData assumes that each line is a CSV data line and tries to convert to a tree. displayTree - if True the tree is printed to standard output after creation colSep - the data separator, a comma by default. headerLine - if True, the first line is stripped off and considered to be the column headings. headerLine can also be a CSV string or a list that defines the column headings. Must have the same number of columns as the rest of the file. verbose - prints diagnositic info to screen if true """ if verbose: print "tree.importData importing file %s" % fname #Error check if isinstance(fname,str): if os.path.exists(fname)==False: print "Can not find file " + fname return #Read in data fid = open(fname,'r') contents = fid.read().split('\n') fid.close() elif isinstance(fname,list): contents=fname #assume that fname is data rather than a file name #Get header data if present if headerLine==True: header = contents.pop(0) header = header.rstrip('\n').split(colSep) elif isinstance(headerLine,str): header = headerLine.rstrip('\n').split(colSep) elif isinstance(headerLine,list): header = headerLine else: header = False data = [] for line in contents: if len(line)==0: continue dataLine = line.split(colSep) if len(header) !=len(dataLine): print "\nTree file appears corrupt! header length is %d but data line length is %d.\ntree.importData is aborting.\n" % (len(header),len(dataLine)) return False theseData = map(int,dataLine[0:2]) #add index and parent to the first two columns #Add data to the third column. Either as a list or as a dictionary (if header names were provided) if header != False: #add as dictionary dataCol = dict() for ii in range(len(header)-2): ii+=2 dataCol[header[ii]]=dataTypeFromString.convertString(dataLine[ii]) else: dataCol = dataLine[2:] #add as list of strings theseData.append(dataCol) data.append(theseData) if verbose: print "tree.importData read %d rows of data from %s" % (len(data),fname) #Build tree tree = Tree() tree.add_node(0) for thisNode in data: tree.add_node(thisNode[0],thisNode[1]) tree[thisNode[0]].data = thisNode[2] #Optionally dump the tree to screen (unlikely to be useful for large trees) if displayTree: tree.display(0) for nodeID in tree.traverse(0): print "%s - %s" % (nodeID, tree[nodeID].data) return tree
treeOfLife["Fish"].data = 'they swim' treeOfLife["Amphibians"].data = 'they croak' treeOfLife["Reptiles"].data = 'they stick to walls' treeOfLife["Mammals"].data = 'they have udders' print "List of nodes:" print treeOfLife.nodes.keys() print "" print "Children of node 'Vertebrates'" print treeOfLife.nodes['Vertebrates'].children print "" print treeOfLife.display('Life') print("\n***** Depth-first *****") for nodeID in treeOfLife.traverse("Life"): print(nodeID) print("\n***** Width-first *****") for nodeID in treeOfLife.traverse("Life", mode=_WIDTH): print(nodeID) print("\n***** Width-first of all data in vertebrates *****") for nodeID in treeOfLife.traverse("Vertebrates", mode=_WIDTH): print "%s - %s" % (nodeID, treeOfLife[nodeID].data) print "\nLeaves:"
def vm_snaps(vm, snaps_tree, root): from collections import deque snaps = deque() snaps.append(vm.find_snapshot("")) snaps_tree.add_node(vm.name, root) last_parent = vm.name while snaps: s = snaps.popleft() snaps_tree.add_node(s.name, last_parent) last_parent = s.name snaps.extend(s.children) if __name__ == "__main__": import sys import virtualbox from tree import Tree sys.coinit_flags = 0 vbox = virtualbox.VirtualBox() snaps_tree = Tree() vm = vbox.find_machine(sys.argv[1]) vm_snaps(vm, snaps_tree, None) snaps_tree.display(vm.name)
3 4 5 6 ''' tree = Tree() tree.add_node("0") # root node tree.add_node("1", "0") tree.add_node("2", "0") tree.add_node("3", "1") tree.add_node("4", "1") tree.add_node("5", "2") tree.add_node("6", "2") tree.add_node("7", "6") tree.add_node("8", "6") tree.add_node("9", "5") tree.add_node("10", "5") tree.display("0") ''' print("***** DEPTH-FIRST ITERATION *****") for node in tree.traverse("Harry"): print(node) print("***** BREADTH-FIRST ITERATION *****") for node in tree.traverse("0", mode=_BREADTH): print(node) '''
from tree import Tree import myconst tree = Tree() tree.add_node("Task") tree.add_node("B1", "Task") tree.add_node("B2", "Task") tree.add_node("B3", "Task") tree.add_node("B4", "B1") tree.add_node("B5", "B2") tree.add_node("L1", "B5") tree.add_node("B6", "B2") tree.add_node("L2", "B6") tree.display("Task") ''' tree.remove_node("B5",myconst.YES) tree.add_node("B5","B2") tree.add_node("L1","B5") tree.display("Task") tree.remove_node("B5",myconst.NO) tree.display("Task") tree.display_dict() print("***** DEPTH-FIRST ITERATION *****") for node in tree.traverse("Task"): print(node) print("***** BREADTH-FIRST ITERATION *****") for node in tree.traverse("Task", mode=BREADTH): print(node)