コード例 #1
0
def test_ispath():
    valid_path = [1, 2, 3, 4]
    invalid_path = [1, 2, 4, 3]
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    edges = [(1, 2), (2, 3), (1, 2), (3, 4)]
    for graph in graphs:
        graph.add_edges_from(edges)
        assert nx.is_path(graph, valid_path)
        assert not nx.is_path(graph, invalid_path)
コード例 #2
0
def find_adapter_chain(adapter_graph: nx.DiGraph) -> tuple[int, int]:
    """Find a valid chain of adapters & determine how many 1 & 3 joltage deltas are present."""
    # NOTE: This approach is super overkill for this problem, but I wanted to stick with the graph
    #
    # Since our edges represent a valid adapter connection, we're looking for a Hamiltonian path
    # here: a path that visits every node exactly once. For this problem, since adapter joltage has
    # to be ascending, we can check a topological sort and see if they're all connected.
    n_one_delta = 0
    n_three_delta = 0
    for check_path in nx.all_topological_sorts(adapter_graph):
        # First check that the topological sort has yielded a valid path.
        if not nx.is_path(adapter_graph, check_path):
            continue

        # Let's assume there's only one valid path
        for source, dest in zip(check_path, check_path[1:]):
            delta = adapter_graph.get_edge_data(source, dest)["delta"]
            if delta == 1:
                n_one_delta += 1
            elif delta == 3:
                n_three_delta += 1

    return n_one_delta, n_three_delta
コード例 #3
0
ファイル: function.py プロジェクト: forking-repos/networkx
def path_weight(G, path, weight):
    """Returns total cost associated with specified path and weight

    Parameters
    ----------
    G : graph
        A NetworkX graph.

    path: list
        A list of node labels which defines the path to traverse

    weight: string
        A string indicating which edge attribute to use for path cost

    Returns
    -------
    cost: int
        A integer representing the total cost with respect to the
        specified weight of the specified path

    Raises
    ------
    NetworkXNoPath
        If the specified edge does not exist.
    """
    multigraph = G.is_multigraph()
    cost = 0

    if not nx.is_path(G, path):
        raise nx.NetworkXNoPath("path does not exist")
    for node, nbr in nx.utils.pairwise(path):
        if multigraph:
            cost += min([v[weight] for v in G[node][nbr].values()])
        else:
            cost += G[node][nbr][weight]
    return cost