def p_matchornot(p): '''matchornot : cmd ELSE cmd | cmd ''' if len(p) > 2: p[0] = Node("matchornot", [p[1],p[3]], [p[2]]) else: p[0] = Node("matchornot", [p[1]])
def test_single_node(self): root = Node("a") root_expected = Node("a") reverse_tree(root) self.assertEqual(root, root_expected)
def bfs(nodes, goal, get_children, explored_set, show=False): frontier = [] if show: print("\n =={}== \n".format(len(nodes))) for node in nodes: children = get_children(node.payload) for child in children: if child not in explored_set: if show: print(child) n_child = Node(child, node) if n_child.equal(goal): sol = [] while n_child is not None: sol.append(n_child.payload) n_child = n_child.parent sol.reverse() return sol explored_set.append(n_child.payload) frontier.append(n_child) if len(frontier) == 0: return None return bfs(frontier, goal, get_children, explored_set, show)
def p_exp(p): '''exp : exp LAND rexp | exp LOR rexp | rexp ''' if len(p) > 2: p[0] = Node("exp", [p[1], p[3]], [p[2]]) else: p[0] = Node("exp", [p[1]])
def p_aexp(p): '''aexp : aexp PLUS mexp | aexp MINUS mexp | mexp''' if len(p) > 2: p[0] = Node("A-exp", [p[1], p[3]], [p[2]]) else: p[0] = Node("A-exp", [p[1]])
def p_mexp(p): '''mexp : mexp TIMES sexp | mexp DIVIDE sexp | sexp''' if len(p) > 2: p[0] = Node("M-exp", [p[1], p[3]], [p[2]]) else: p[0] = Node("M-exp", [p[1]])
def p_metodo(p): "metodo : PUBLIC tipo ID LPAREN paramsopcional RPAREN LBRACE variaveis cmds RETURN exp SEMI RBRACE " if(len(p) < 14): tokens = [p[1], p[3], p[4], p[5], p[6], p[9], p[11], p[12]] p[0] = Node("metodo", [p[2], p[7], p[8], p[10]], tokens) else: tokens = [p[1], p[3], p[4], p[6], p[7], p[10], p[12], p[13]] p[0] = Node("metodo", [p[5], p[2], p[8], p[9], p[11]], tokens)
def p_rexp(p): '''rexp : rexp LT aexp | rexp EQ aexp | rexp NE aexp | aexp''' if len(p) > 2: p[0] = Node("R-exp", [p[1], p[3]], [p[2]]) else: p[0] = Node("R-exp", [p[1]])
def p_tipo(p): '''tipo : INT LBRACK RBRACK | BOOL | INT | ID ''' if( len(p) > 2): tokens = [p[1],p[2],p[3]] p[0] = Node("tipo", leaf=tokens) else: p[0] = Node("tipo", leaf=[p[1]])
def p_listaparamsextra(p): '''listaparamsextra : listaparamsextra COMMA tipo ID | ''' if len(p) == 5: tokens = [p[2], p[4]] p[0] = Node("BNF-paramsExtra", [p[1], p[3]], tokens) if len(p) == 4 : tokens = [p[1], p[3]] p[0] = Node("BNF-paramsExtra", [p[2]], tokens)
def test_tree_with_duplicate_data(self): root0 = Node(3) root0.left = Node(3) root0.left.right = Node(1) root1 = Node(3) root1.right = Node(1) is_subtree_expected = True self.assertEqual(is_subtree(root0, root1), is_subtree_expected)
def test_provided_example_2(self): """Can't use other methods as this has a duplicated node data in it""" root0 = Node(26) root0.left = Node(10) root0.right = Node(3) root0.right.right = Node(3) root0.left.left = Node(4) root0.left.right = Node(6) root0.left.right.left = Node(30) node_des1 = [(10, 4, "L"), (10, 6, "R"), (4, 30, "R")] root1 = TreeMaker.from_node_description(node_des1) is_subtree_expected = False self.assertEqual(is_subtree(root0, root1), is_subtree_expected)
def prepare_data(): root = Node(3) root.left = Node(9) root.right = Node(20) root.right.left = Node(15) root.right.right = Node(7) return root
def solution_018(file: str = "data/project_euler/p018_triangle.txt") -> int: with open(file=file, mode="r") as file_handle: triangle_str = file_handle.read() triangle_matrix = [[int(num_str) for num_str in row_str.split()] for row_str in triangle_str.strip().split("\n")] node = Node.from_triangle_matrix(triangle_matrix=triangle_matrix) return sum(node.maximal_path)
class Test(unittest.TestCase): @parameterized.expand([ ("1 level", [(1, 2, "L"), (1, 3, "R")], [2, 1, 3]), ("LHS view", [(1, 2, "L"), (2, 4, "L")], [4, 2, 1]), ("RHS view", [(1, 3, "R"), (3, 7, "R")], [1, 3, 7]), ("Replace node", [(1, 2, "L"), (2, 5, "R")], [2, 5]), ("Same position, right most", [(1, 2, "L"), (1, 3, "R"), (2, 5, "R"), (3, 6, "L")], [2, 6, 3]), ("Depth beats order", [("0", "0L", "L"), ("0", "0R", "R"), ("0L", "0LR", "R"), ("0LR", "0LRR", "R")], ["0L", "0LR", "0LRR"]), ("Provided example 0", [(20, 8, "L"), (20, 22, "R"), (8, 5, "L"), (8, 3, "R"), (3, 10, "L"), (3, 14, "R"), (22, 25, "R")], [5, 10, 3, 14, 25]), ("Provided example 1", [(20, 8, "L"), (20, 22, "R"), (8, 5, "L"), (8, 3, "R"), (3, 10, "L"), (3, 14, "R"), (22, 4, "L"), (22, 25, "R")], [5, 10, 4, 14, 25]) ]) def test_trees(self, _, node_description, expected_bottom_view): root, num_nodes = TreeMaker.tree_and_node_count_from_node_description( node_description) self.assertEqual(bottom_view(root, num_nodes), expected_bottom_view) @parameterized.expand([("Null test", None, []), ("Single node", Node(1), [1])]) def test_corner_cases(self, _, node, expected_bottom_view): self.assertEqual(bottom_view(node, 1), expected_bottom_view)
def bfs(self): frontier = [] for node in self.nodes: children = self.get_children(node.payload) print("=== {} ===".format(len(self.nodes))) for child in children: if child not in self.explored_set: print(child) n_child = Node(child, node) self.explored_set.append(n_child.payload) frontier.append(n_child) with lock: if n_child.payload in self.goals.keys(): sol = [] while n_child is not None: sol.append(n_child.payload) n_child = n_child.parent self.sol = sol return self.goals[child] = n_child if len(frontier) == 0: return None self.nodes = frontier return self.bfs()
def p_pexp(p): '''pexp : ID | THIS | NEW ID LPAREN RPAREN | LPAREN exp RPAREN | pexp POINT ID LPAREN expopcionalmetodo RPAREN | pexp POINT ID LPAREN RPAREN | pexp POINT ID''' non_terms = [] tokens = [] if(type(p[1]) != Node): tokens.append(p[1]) if len(p) == 5: tokens.extend([p[2],p[3],p[4]]) elif len(p) == 4: tokens.append(p[3]) non_terms.append(p[2]) else: non_terms.append(p[1]) tokens.extend([p[2],p[3]]) if(len(p) > 4): if p[5] == ')': tokens.extend([p[4],p[5]]) else: non_terms.append(p[5]) tokens.extend([p[4],p[6]]) p[0] = Node("P-exp", non_terms, tokens)
def p_sexp(p): # MINUS sexp ? '''sexp : LNOT sexp | MINUS sexp | TRUE | FALSE | NUMBER | NULL | NEW INT LBRACK exp RBRACK | pexp POINT LENGTH | pexp LBRACK exp RBRACK | pexp ''' tokens = [] non_terms = [] if type(p[1]) != Node: tokens.append(p[1]) if p[1] == '!' or p[1]== '-': non_terms.append(p[2]) if p[1] == 'new': non_terms.append(p[4]) tokens.extend([p[2],p[3],p[5]]) else: non_terms.append(p[1]) if len(p) == 4: tokens.extend([p[2],p[3]]) elif len(p) == 5: non_terms.append(p[3]) tokens.extend([p[2],p[4]]) p[0] = Node("S-exp", non_terms, tokens)
def _ingest_export(export: ExportTableItem, loader: AssetLoader): current_cls: ExportTableItem = export segment: Optional[Node[str]] = None fullname = current_cls.fullname assert fullname # We may have already covered this while traversing parents if fullname in tree: return while True: # Extend unsaved segment old_segment = segment segment = Node(fullname) if old_segment: segment.add(old_segment) # Get name of parent class parent_name = _get_parent_cls(current_cls) if not parent_name: raise MissingParent(f'Unable to find parent of {fullname}') # Is the parent present in the tree? anchor_point = tree.get(parent_name, None) # If we've risen outside /Game but didn't find a match, add it to the root and complain if not anchor_point and not parent_name.startswith('/Game'): logger.warning( f'Internal class {parent_name} missing from pre-defined hierarchy' ) tree.add(ROOT_NAME, parent_name) anchor_point = tree.get(parent_name, None) if anchor_point: # Insert segment and finish tree.insert_segment(parent_name, segment) return # Load parent class and replace current parent_cls = loader.load_class(parent_name) current_cls = parent_cls fullname = current_cls.fullname assert fullname
def launch_search_bidirectional(url_start, url_goal): url_start = Node(url_start) url_goal = Node(url_goal) dico = {url_start.payload: url_start, url_goal.payload: url_goal} bfs1 = Bi_Bfs(url_start, dico, get_urls) bfs2 = Bi_Bfs(url_goal, dico, get_urls) bfs1.start() bfs2.start() bfs1.join() bfs2.join() sol = bfs1.sol[1:] sol.reverse() sol.extend(bfs2.sol) return sol
def p_assignment(p): '''assignment : ID ASSIGN exp SEMI | ID LBRACK exp RBRACK ASSIGN exp SEMI ''' tokens =[] non_terms =[] non_terms.append(p[3]) if(p[2] == '='): tokens.extend([p[1],p[2],p[4]]) else: tokens.extend([p[1], p[2], p[4],p[5],p[7]]) non_terms.append(p[6]) p[0] = Node("assignment", non_terms, tokens)
class Test(unittest.TestCase): @parameterized.expand([("Single level full", [(1, 2, "L"), (1, 3, "R")], True), ("Single level not full", [(1, 2, "L")], False), ("provided example 0", [(1, 2, "L"), (1, 3, "R"), (2, 4, "L"), (2, 5, "R")], True), ("provided example 1", [(1, 2, "L"), (1, 3, "R"), (2, 4, "L")], False)]) def test_trees(self, _, node_description, is_full_expected): root = TreeMaker.from_node_description(node_description) self.assertEqual(is_full_binary_tree(root), is_full_expected) @parameterized.expand([("Null test", None, True), ("Single node", Node(0), True)]) def test_corner_cases(self, _, root, is_full_expected): self.assertEqual(is_full_binary_tree(root), is_full_expected)
def p_otherstmt(p): '''otherstmt : LBRACE cmds RBRACE | WHILE LPAREN exp RPAREN cmd | SOUTPL LPAREN exp RPAREN SEMI | assignment''' non_terms = [] tokens = [] if(p[1] != '{' and type(p[1]) != Node): non_terms.append(p[3]) if(p[1] == 'while'): non_terms.append(p[5]) tokens.extend([p[1],p[2],p[4]]) else: tokens.extend([p[1],p[2],p[4],p[5]]) else: if (len(p) > 3) : non_terms.append(p[2]) tokens.extend([p[1],p[3]]) else: non_terms.append(p[1]) p[0] = Node("otherstmt", non_terms, tokens)
def p_variaveis(p): '''variaveis : variaveis var |''' if len(p) > 2: p[0] = Node("BNF-variaveis", [p[1], p[2]])
def p_extends(p): '''extends : EXTENDS ID |''' if len(p) > 2: tokens = [p[2],p[1]] p[0] = Node("BNF-extends", leaf=tokens)
def p_metodos(p): '''metodos : metodos metodo | ''' if len(p) > 2: p[0] = Node("BNF-metodo", [p[1], p[2]])
def p_var(p): "var : tipo ID SEMI" tokens = [p[2],p[3]] p[0] = Node("var", [p[1]], tokens)
def p_params(p): '''params : tipo ID listaparamsextra''' tokens = [p[2]] p[0] = Node("params", [p[1], p[3]], tokens)
def p_cmds(p): '''cmds : cmds cmd | ''' if len(p) >= 2: p[0] = Node("BNF-cmd", [p[1], p[2]])
def p_paramsopcional(p): '''paramsopcional : params | ''' if len(p) >= 2: p[0] = Node("BNF-params", [p[1]])