def part2(raw_orbits, node1_name, node2_name, print_tree=False): orbit_map = generate_orbit_map(raw_orbits, print_tree=print_tree) node1 = orbit_map[node1_name] node2 = orbit_map[node2_name] ca = commonancestors(node1, node2)[-1] orbital_transfers = 0 for node in (node1, node2): a = commonancestors(node.parent) orbital_transfers += len(a[a.index(ca):]) return orbital_transfers
def test_commonancestors(): """commonancestors.""" udo = Node("Udo") marc = Node("Marc", parent=udo) dan = Node("Dan", parent=udo) jet = Node("Jet", parent=dan) joe = Node("Joe", parent=dan) eq_(commonancestors(jet, joe), (udo, dan)) eq_(commonancestors(jet, marc), (udo, )) eq_(commonancestors(jet), (udo, dan)) eq_(commonancestors(), ())
def leaves_to_vector(leaves): """ given a list of leaf nodes, return the pairwise path length in the order (0,1), (0,2) ... ,(0, i), (1, 2), (1, 3) ,..., (i-1, i) where i is the index of the last leaf node :param leaves:list(nodes) :return:list(int) """ vector = [] num_of_leaves = len(leaves) for i in range(num_of_leaves): for j in range(i+1, num_of_leaves): node1 = leaves[i] node2 = leaves[j] ancestor_list = list(commonancestors(node1, node2)) # The node with maximum string length corresponds to the lowest common ancestor(LCA) # Because the string is composed of path from root to the node # For example, in ["Node('/tree1')", "Node('/tree1/*0')", "Node('/tree1/*0/*1')"], # "Node('/tree1/*0/*1')" has maximum length, and must be LCA len_str_list = [len(str(item)) for item in ancestor_list] lowest_common_ancestor = ancestor_list[len_str_list.index(max(len_str_list))] path_length1 = path_length_to_ancestor(node1, lowest_common_ancestor) # path length from node1 to LCA path_length2 = path_length_to_ancestor(node2, lowest_common_ancestor) # path length from node2 to LCA total_length = path_length1 + path_length2 vector.append(total_length) # print("{0}\t{1}\t{2}".format # (leaves[i].name, leaves[j].name, lowest_common_ancestor.name)) # print("total path length: ", total_length) return vector
def part1(raw_orbits, print_tree=False): orbit_map = generate_orbit_map(raw_orbits, print_tree=print_tree) total_orbits = 0 for node in PreOrderIter(orbit_map['COM']): ca = commonancestors(node) total_orbits += len(ca) return total_orbits
def generate_graph(num_nodes, num_odd_sets, size_odd_sets, identifier, weighted): nodes = list(range(num_nodes)) edges = [] objective = [] random.seed(identifier) for t in range(num_odd_sets): subset = random.sample(nodes, size_odd_sets) for e in [(i, j) for i in subset for j in subset if i < j]: if e not in edges: edges.append(e) objective.append(1) radix = 3 # 2 makes binary tree, 3 makes trinary tree # odd radix means only odd sets sets = [] dict = {} cnt = 0 for i in nodes: dict[i] = Node(i, size=1) sets.append(dict[i]) while len(sets) >= radix: node = Node('i', ident = cnt) cnt += 1 siz = 0 for c in range(radix): idx = random.randint(0,len(sets)-1) sets[idx].parent = node siz = siz + sets[idx].size del sets[idx] node.size = siz sets.append(node) if weighted == 1: for i in range(len(edges)): # if e is in S, add to e's weight 2/(|S| - 1) weight = 0 for an in commonancestors(dict[edges[i][0]],dict[edges[i][1]]): weight = weight + 2./(an.size - 1) objective[i] = weight return nodes, edges, objective
def check_for_identical_subtree_cousins(self, root_node): longest_repeating_nodes = self.longest_repeated_substring( self.tree_traversal) if longest_repeating_nodes == list(): return self.create_response(), False node_1 = longest_repeating_nodes[0] node_2 = longest_repeating_nodes[1] common_ancestors = commonancestors(node_1, node_2) if len(common_ancestors) > 0: lowest_common_ancestor = common_ancestors[-1] node_1_ht = len(node_1.path) node_2_ht = len(node_2.path) offset_ht = len(lowest_common_ancestor.path) if offset_ht > 1 and node_1_ht - offset_ht == node_2_ht - offset_ht: path_1_arr = self.get_path_array(node_1) path_2_arr = self.get_path_array(node_2) return self.create_response([path_1_arr, path_2_arr], list(), list()), True else: return self.create_response(), False else: return self.create_response(), False
def choose_table(root, word): node = search.find_by_attr(root, word) b = util.commonancestors(node)[1].name return b
TREE[B] = Node(B) TREE[B].parent = TREE[A] return (TREE['COM'], TREE) def calculateOrbits(TREE): TOTAL = 0 for K in TREE.keys(): TOTAL += len(TREE[K].anchestors) print(TOTAL) ROOT, TREE = constructTree("orbits2.txt") FIRST_COMMON_ANCESTOR = commonancestors(TREE["YOU"], TREE["SAN"])[-1] def distanceToTargetNode(Node, Target): DISTANCE = 0 ANCH = list(Node.anchestors) ANCH.reverse() for A in ANCH: if A == Target: break else: DISTANCE += 1 #print(DISTANCE) return DISTANCE
def get_common_ancestors(p1, p2): return commonancestors(p1, p2)
from anytree.util import commonancestors, leftsibling, rightsibling inputs = [] input_file = os.path.join(os.path.dirname(__file__), 'input.txt') with open(input_file) as f: inputs = f.read().splitlines() # inputs = ['COM)B','B)C','C)D','D)E','E)F','B)G','G)H','D)I','E)J','J)K','K)L','K)YOU','I)SAN',] orbit_map = {} for i in inputs: obj, in_orbit = i.split(')') if obj not in orbit_map: orbit_map[obj] = Node(obj) if in_orbit in orbit_map: # set parent orbit_map[in_orbit].parent = orbit_map[obj] else: orbit_map[in_orbit] = Node(in_orbit, parent=orbit_map[obj]) ca = commonancestors(orbit_map['YOU'], orbit_map['SAN'])[-1] you_a = commonancestors(orbit_map['YOU'].parent) you_dist = len(you_a[you_a.index(ca):]) san_a = commonancestors(orbit_map['SAN'].parent) san_dist = len(san_a[san_a.index(ca):]) print(you_dist + san_dist)
# inputs = ['COM)B', 'B)C', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L'] # inputs = ['B)C', 'COM)B', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L'] # inputs = ['B)C', 'COM)B', 'C)D', 'E)F', 'B)G', 'D)E', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L'] orbit_map = {} for i in inputs: obj, in_orbit = i.split(')') if obj not in orbit_map: orbit_map[obj] = Node(obj) if in_orbit in orbit_map: # update parent orbit_map[in_orbit].parent = orbit_map[obj] else: orbit_map[in_orbit] = Node(in_orbit, parent=orbit_map[obj]) total_orbits = 0 seen_orbits = set() # print(RenderTree(orbit_map['COM'])) for node in PreOrderIter(orbit_map['COM']): ca = commonancestors(node) # print(node.name, ca) total_orbits += len(ca) print(total_orbits)
else: orbiterNode = Node(orbiter, parent=centerNode) return COM def verifymap(orbitmap): """Verifies an orbitmap, returns the checksum >>> verifymap(readmap("COM)B\\nB)C\\nC)D\\nD)E\\nE)F\\nB)G\\nG)H\\nD)I\\nE)J\\nJ)K\\nK)L")) 42 """ count = 0 orbiters = findall(orbitmap, filter_=lambda node: node.name != "COM") for orbiter in orbiters: count += orbiter.depth return count if __name__ == "__main__": with open("data") as data: orbitmap = data.readlines() orbitmap = readmap(orbitmap) YOU = find_by_attr(orbitmap, "YOU") SAN = find_by_attr(orbitmap, "SAN") ancestors = commonancestors(YOU.parent, SAN.parent) print("To move from YOU's parent to SAN's parent requires: %d" % (YOU.parent.depth + SAN.parent.depth - 2 * ancestors[-1].depth))