This guide shows how to use graphkit interactively from the command line (using the Python REPL) or inside scripts.
Install first:
pip install pygraphkitStart Python:
pythonImport the core graph abstraction:
from graphkit import Graphg = Graph()
g.add_edge(1, 2, 4)
g.add_edge(2, 3, 1)g = Graph(directed=True)
g.add_edge("A", "B", 5)dist = g.dijkstra(source)Example:
g = Graph()
g.add_edge(1, 2, 4)
g.add_edge(1, 3, 1)
g.add_edge(3, 2, 2)
print(g.dijkstra(1))Output:
{1: 0, 2: 3, 3: 1}
dist = g.bellman_ford(source)If a negative cycle exists:
ValueError: Negative cycle detected
dist = g.floyd_warshall()Access distances:
dist[u][v]mst, total_weight = g.kruskal()mst, total_weight = g.prim(start_node)order = g.bfs(source)order = g.dfs(source)order = g.topological_sort()If the graph contains a cycle:
ValueError: Graph contains a cycle
components = g.strongly_connected_components()Each component is returned as a list of nodes.
Flow algorithms use a separate abstraction.
from graphkit.flow import FlowGraphg = FlowGraph()
g.add_edge(0, 1, 3)
g.add_edge(1, 2, 2)
max_flow = g.max_flow(0, 2)max_flow, (S, T) = g.max_flow_with_min_cut(0, 2)S: vertices reachable from source in residual graphT: remaining vertices
- Nodes can be any hashable type (int, str, tuple, etc.)
- Algorithms raise
ValueErroron invalid usage - The public API is stable starting from v1.0.0