Ejemplo n.º 1
0
 def find_path(self, srcid, dstid):
     """
     method that receives a source node and a destination one. It will check if two nodes are directly
     connected.
     :param srcid: the node's id from which we will start to iterate
     :param dstid: the node's id we want to know if it's connected to source.
     :return: path: the list of nodes that will lead from source to dest.
     """
     source = self.find_node(srcid + 2)
     dest = self.find_node(dstid + 2)
     if source is dest:
         return [source.get_id()]
     w = Walker()
     walk_path = w.walk(source, dest)
     up = walk_path[0]
     common = walk_path[1]
     down = walk_path[2]
     uplist = [e for e in up]
     downlist = [e for e in down]
     uplist.append(common)
     uplist.extend(down)
     path = [source.get_id()]
     for node in uplist:
         path.append(node.get_id())
     return path
Ejemplo n.º 2
0
 def travel_tree(self):
     self.travel_list = []
     tree_walker = Walker()
     print("Begin Travel Tree")
     for item in sorted(self.id_node_dict.keys()):
         node = self.id_node_dict[int(item)]
         paths, _, _ = tree_walker.walk(node, self.root)
         paths = list(paths)
         paths.reverse()
         travel = [self.keycode_nodeid_dict[i.key_code] for i in paths]
         while len(travel) < self.max_level:
             travel.append(0)
         self.travel_list.append(travel)
Ejemplo n.º 3
0
 def change_context(self,new_context_type,new_context_command):
     """
     change current context to new_context name
     :param new_context_type: the type of context we want to switch to e.g. "interface vlan" | "interface_vlan"
     should be in self._support_contexts
     :param new_context_command: the actual command to switch to context e.g. "interface vlan 5"
     :return: True upon success or False otherwise
     :rtype:bool
     """
     funcname = GetFunctionName(self.change_context)
     ret = True
     if not self.context:
         try:
             self._detect_context()
         except TestCrashedException as e:
             # failed to detect context
             ret = False
             err = funcname+" failed to detect current context, can't continue\n"
             GlobalLogger.logger.error(err)
             return ret
     new_context = CliContextNode._normalize_name(new_context_type)
     if new_context in self._support_contexts:
         from anytree.walker import Walker,WalkError
         # start search the context in the relevant tree
         w = Walker()
         err = None
         for context_tree in self._context_trees:
             # type: CliContextNode
             try:
                 path = w.walk(self.context,new_context)
                 ret = True
                 pass
             except WalkError as we:
                 err = funcname+ " Failed to change context using tree walker got exception: {}".format(str(we))
             except Exception as e:
                 err = funcname+ " Failed to change context got exception: {}".format(str(e))
             finally:
                 if err:
                     GlobalLogger.logger.error(err)
                     ret = False
             return ret
Ejemplo n.º 4
0
def main():
    # requests a word from the user
    query = input("Enter a word:\n> ")
    if query not in wordset:
        print("That's not a word.")
        return
    print("Processing (this could take a few seconds)...\n")

    # sets the root node to the user's input
    root_node = Node(query)
    # finds direct descendants of root word
    dig(query, root=root_node)

    while funnel_queue:
        for index, word_dict in enumerate(funnel_queue):
            # finds direct descendants of all words in funnel queue
            funnel_queue.pop(index)
            dig(word_dict["word"], parent=word_dict["parent_node"])

    print(f"Longest funnel length: {(root_node.height + 1) if root_node.height > 0 else 0}\n"
          f"\n"
          f"Longest funnel(s):")

    longest_funnels = set()  # creates a set to hold the root word's longest funnel(s)

    # iterates through each of the deepest child nodes, adding string representations of the paths from
    # the root node to each child node to longest_funnels
    for child_node in [child for child in root_node.descendants if child.depth == root_node.height]:
        walk_path = list(Walker().walk(root_node, child_node)[2])
        walk_path.insert(0, root_node)
        funnel_string = ""
        for node in walk_path:
            funnel_string += node.name + (' -> ' if node != walk_path[-1] else "")
        longest_funnels.add(funnel_string)
    if longest_funnels:
        # prints the paths of each longest funnel
        for funnel in sorted(longest_funnels):
            print(funnel)
    else:
        print("No funnels")
Ejemplo n.º 5
0
def orbDist(map, node1, node2):
    return Walker().walk(node1, node2)
Ejemplo n.º 6
0
        input_nodes.add(child)
        input_edges.append((parent, child))

print(f'input_nodes: {input_nodes}')
print(f'input_edges: {input_edges}')

edge_dict = {child: parent for parent, child in input_edges}
nodes = [Node(input_node) for input_node in input_nodes]
node_dict = {node.name: node for node in nodes}

for node in nodes:
    if node.name != "COM":
        parent_string = edge_dict[node.name]
        node.parent = node_dict[parent_string]

root = node_dict["COM"]

for pre, fill, node in RenderTree(root):
    print("%s%s" % (pre, node.name))

you = node_dict["YOU"]
santa = node_dict["SAN"]

w = Walker()
my_walk = w.walk(you, santa)
print(my_walk)
upwards, common, downwards = my_walk
length = len(upwards) + 1 + len(
    downwards) - 3  # Don't count YOU, SAN, or the orbit you start at
print(f'length: {length}')
Ejemplo n.º 7
0
	# find if child is already a subtree
	childIdx = -1
	for t in range(len(trees)):
		if trees[t].name == data[i,1]:
			childIdx = t
	if childIdx != -1:
		# subtree found, remove subtre and append to other tree
		child = trees.pop(childIdx)
		child.parent = parent
	else:
		# make new child
		child = Node(data[i,1], parent=parent)

		
w = Walker()
		
		
# part 1
total = 0
for node in PreOrderIter(trees[0]):
	nodes = w.walk(trees[0], node)
	total += (len(nodes[2]))
print("Part 1: ", total)	
	

# part 2
you = find(trees[0], lambda node: node.name == "YOU")
san = find(trees[0], lambda node: node.name == "SAN")
nodesToStep = w.walk(you, san)
def calculateOrbitTransfers(orbits, start, end):
    w = Walker()
    path = w.walk(start, end)
    return len(path[0]) + len(path[2])