<jupyter_start><jupyter_text>DAGs - no. of paths of length $k$For adjacency matrix $A$, representimng a DAG $G$, no. of paths between nodes $i$ and $j$ of length $k$ can be identified by raising $A$ to the power of $k$:$$\Large A^k_{ij} = \text{no. of paths of len $k$ from $i$ to $j$}$$<jupyter_code>def get_n_paths_of_len_k(graph, node_0, node_1, k):
    
    """Computes a number ogf paths of len k between nodes i and j"""
    
    A = nx.linalg.graphmatrix.adjacency_matrix(graph).todense()
    paths_k = np.linalg.matrix_power(A, k)
    
    return paths_k[node_0, node_1]<jupyter_output><empty_output><jupyter_text>Build a graph<jupyter_code># Create a graph
G = nx.DiGraph()

# Add nodes
G.add_nodes_from(np.arange(6))

# Add edges
G.add_edges_from(
    [
        (0, 1),
        (0, 3),
        (0, 5),
        (1, 2),
        (2, 5),
        (3, 4),
        (4, 5)
    ]
)
# Plot the graph
nx.draw(G, with_labels=True)
# Get the adjacency matrix
A = nx.linalg.graphmatrix.adjacency_matrix(G).todense()
A<jupyter_output><empty_output><jupyter_text>We expect to have $2$ paths of length $3$ from node $0$ to node $5$. Let's check it:<jupyter_code>get_n_paths_of_len_k(
    graph=G, 
    node_0=0, 
    node_1=5, 
    k=3
)<jupyter_output><empty_output><jupyter_text>$G$ is directed, so we expect to have one path of len $2$ from node $3$ to node $5$:<jupyter_code>get_n_paths_of_len_k(
    graph=G, 
    node_0=3, 
    node_1=5, 
    k=2
)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13879485443466485, 'fraction_numerical': 0.024373730534867976, 'mean_word_length': 3.5337423312883436, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '367924', 'license': 'MIT', 'n_tokens_mistral': 634, 'n_tokens_neox': 611, 'n_words': 156, 'path': 'graphs/00 - DAG - identify no. of paths of len k.ipynb', 'repo_name': 'AlxndrMlk/math', 'size': '1477'}