Skip to content

Instantly share code, notes, and snippets.

@kiwiyou
Created January 20, 2024 03:06
Show Gist options
  • Save kiwiyou/4f2a174028e6af2b468e16e8174207a3 to your computer and use it in GitHub Desktop.
Save kiwiyou/4f2a174028e6af2b468e16e8174207a3 to your computer and use it in GitHub Desktop.
PyPy Compressed Sparse Row
from array import array
class Graph:
def __init__(self, N):
self.h = array('I', [1 << 30]) * N
self.l = array('I')
self.e = array('I')
def connect(self, u, v):
p = self.h[u]
self.h[u] = len(self.l)
self.l.append(p)
self.e.append(v)
def iter(self, u):
it = GraphIter()
it.l = self.l
it.e = self.e
it.i = self.h[u]
return it
class GraphIter:
__slots__ = ('l', 'e', 'i')
def __iter__(self):
return self
def __next__(self):
if self.i == 1 << 30:
raise StopIteration
v = self.e[self.i]
self.i = self.l[self.i]
return v
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment