Adjacency from an edge list. Each edge is [a, b] or, with weighted,
[a, b, w]. Unweighted returns a dict of lists in edge order; weighted a
dict of dicts, adj[a][b] = w. With n, nodes 0 to n - 1 are all keys,
isolated ones with an empty list. reverse reads each edge as b to a.
directed=False adds both directions.
Source code in pydsa/adj.mu
7 8 9101112131415161718192021222324252627282930
defadjacency(edges:list,n:int?=none,reverse:bool=false,directed:bool=true,weighted:bool=false)"""Adjacency from an edge list. Each edge is [a, b] or, with weighted, [a, b, w]. Unweighted returns a dict of lists in edge order; weighted a dict of dicts, `adj[a][b] = w`. With n, nodes 0 to n - 1 are all keys, isolated ones with an empty list. reverse reads each edge as b to a. directed=False adds both directions."""retadj=weighted?{:dict}:{:list}forcin0..<(nor0)adj[c]foreinedgesa,b=e[:2]ifreversea,b=b,aifweightedadj[a][b]=e[2]ifnotdirectedadj[b][a]=e[2]elseadj[a]<-bifnotdirectedadj[b]<-a
28293031323334353637383940414243444546474849
defadjacency(edges:list,n:Optional[int]=None,reverse:bool=False,directed:bool=True,weighted:bool=False):"""Adjacency from an edge list. Each edge is [a, b] or, with weighted, [a, b, w]. Unweighted returns a dict of lists in edge order; weighted a dict of dicts, `adj[a][b] = w`. With n, nodes 0 to n - 1 are all keys, isolated ones with an empty list. reverse reads each edge as b to a. directed=False adds both directions."""adj=defaultdict(dict)ifweightedelsedefaultdict(list)forcinrange(0,(nor0)):adj[c]foreinedges:a,b=e[:2]ifreverse:a,b=b,aifweighted:adj[a][b]=e[2]ifnotdirected:adj[b][a]=e[2]else:adj[a].append(b)ifnotdirected:adj[b].append(a)returnadj
In-degree of every node from an edge list, each edge [a, b] counting
one into b. Default is a defaultdict(int), any node reading 0; with n,
nodes 0 to n - 1 are all keys. type=list needs n and returns a plain
list. reverse reads each edge as b to a. directed=False counts the edge
into a as well, so the result is the plain degree of every node.
Source code in pydsa/adj.mu
323334353637383940414243444546474849
defindegrees(edges:list,n:int?=none,reverse:bool=false,directed:bool=true,type=defaultdict)"""In-degree of every node from an edge list, each edge [a, b] counting one into b. Default is a defaultdict(int), any node reading 0; with n, nodes 0 to n - 1 are all keys. type=list needs n and returns a plain list. reverse reads each edge as b to a. directed=False counts the edge into a as well, so the result is the plain degree of every node."""iftypeislistandnisnoneraiseValueError("type=list needs n")retindeg=typeislist?table(n):defaultdict(int,dict.fromkeys(0..<(nor0),0))foreinedgesa,b=e[:2]ifreversea,b=b,aindeg[b]+=1ifnotdirectedindeg[a]+=1
5253545556575859606162636465666768
defindegrees(edges:list,n:Optional[int]=None,reverse:bool=False,directed:bool=True,type=defaultdict):"""In-degree of every node from an edge list, each edge [a, b] counting one into b. Default is a defaultdict(int), any node reading 0; with n, nodes 0 to n - 1 are all keys. type=list needs n and returns a plain list. reverse reads each edge as b to a. directed=False counts the edge into a as well, so the result is the plain degree of every node."""iftypeislistandnisNone:raiseValueError("type=list needs n")indeg=table(n)iftypeislistelsedefaultdict(int,dict.fromkeys(range(0,(nor0)),0))foreinedges:a,b=e[:2]ifreverse:a,b=b,aindeg[b]+=1ifnotdirected:indeg[a]+=1returnindeg
Level-order BFS over a deque the caller keeps pushing onto.
Yields (d, item) for every item popped, where d is the level the item
was pushed at, starting from 0 for the items already in q. The caller
appends the next level's items to q inside the loop body. With grouped=True
yields (d, items) once per level, items being the whole level as a list.
Every popped item is checked before it is yielded. With eq, lt, lte, gt or
gte, an item whose value fails one of them is dropped; the value is
grid[item[0]][item[1]] when grid is given, else the item itself. With
seen, an item already in seen is dropped and a kept item is added to it,
so the caller can push without checking.
deflevels(q:Deque,grid=none,seen:set?=none,grouped:bool=false,eq=none,lt=none,lte=none,gt=none,gte=none)->Iterator[(int,Any)]"""Level-order BFS over a deque the caller keeps pushing onto. Yields (d, item) for every item popped, where d is the level the item was pushed at, starting from 0 for the items already in q. The caller appends the next level's items to q inside the loop body. With grouped=True yields (d, items) once per level, items being the whole level as a list. Every popped item is checked before it is yielded. With eq, lt, lte, gt or gte, an item whose value fails one of them is dropped; the value is `grid[item[0]][item[1]]` when grid is given, else the item itself. With seen, an item already in seen is dropped and a kept item is added to it, so the caller can push without checking. """defkeep(x)->boolv=gridisnone?x:grid[x[0]][x[1]]ifnot_holds(v,eq,lt,lte,gt,gte)or(seenisnotnoneandxinseen)returnfalseifseenisnotnoneseen.add(x)trued=0whileqpopped=(q.popleft()for_in0..<lenq)ifgroupediflevel:=[xforxinpoppedifkeep(x)]yieldd,levelelseforxinpoppedifkeep(x)yieldd,xd+=1
deflevels(q:Deque,grid=None,seen:Optional[set]=None,grouped:bool=False,eq=None,lt=None,lte=None,gt=None,gte=None)->Iterator[tuple[int,Any]]:"""Level-order BFS over a deque the caller keeps pushing onto. Yields (d, item) for every item popped, where d is the level the item was pushed at, starting from 0 for the items already in q. The caller appends the next level's items to q inside the loop body. With grouped=True yields (d, items) once per level, items being the whole level as a list. Every popped item is checked before it is yielded. With eq, lt, lte, gt or gte, an item whose value fails one of them is dropped; the value is `grid[item[0]][item[1]]` when grid is given, else the item itself. With seen, an item already in seen is dropped and a kept item is added to it, so the caller can push without checking. """defkeep(x)->bool:v=xifgridisNoneelsegrid[x[0]][x[1]]ifnot_holds(v,eq,lt,lte,gt,gte)or(seenisnotNoneandxinseen):returnFalseifseenisnotNone:seen.add(x)returnTrued=0whileq:popped=(q.popleft()for_inrange(0,len(q)))ifgrouped:iflevel:=[xforxinpoppedifkeep(x)]:yieldd,levelelse:forxinpopped:ifkeep(x):yieldd,xd+=1
The connected components of a graph given as its vertices and a
function edges(u) listing u's neighbours, each as a list of vertices.
Source code in pydsa/adj.mu
88 89 90 91 92 93 94 95 96 97 98 99100101
defcomponents(vertices,edges)"""The connected components of a graph given as its vertices and a function edges(u) listing u's neighbours, each as a list of vertices."""retout,left=[],set(vertices)whileleftstack,comp=[left.pop()],[]whilestacku=stack.comp<-uforvinedges(u)ifvinleftleft.remove(v)stack<-vout<-comp
105106107108109110111112113114115116117118119
defcomponents(vertices,edges):"""The connected components of a graph given as its vertices and a function edges(u) listing u's neighbours, each as a list of vertices."""out,left=[],set(vertices)whileleft:stack,comp=[left.pop()],[]whilestack:u=stack.pop()comp.append(u)forvinedges(u):ifvinleft:left.remove(v)stack.append(v)out.append(comp)returnout
Shortest distance from src to every vertex of g, inf when unreachable.
Source code in pydsa/adj.mu
118119120121122123124125126127128129130
defdijkstra(g,src)"""Shortest distance from src to every vertex of g, inf when unreachable."""retdist={u:infforuing.vertices}dist[src]=0pq=[(0,src)]whilepqd,u=heappop(pq)ifd>dist[u]continueforv,wing.adj[u]ifd+w<dist[v]dist[v]=d+wheappush(pq,(d+w,v))
140141142143144145146147148149150151152153
defdijkstra(g,src):"""Shortest distance from src to every vertex of g, inf when unreachable."""dist=Rec({u:infforuing.vertices})dist[src]=0pq=[(0,src)]whilepq:d,u=heappop(pq)ifd>dist[u]:continueforv,wing.adj[u]:ifd+w<dist[v]:dist[v]=d+wheappush(pq,(d+w,v))returndist