Skip to content

Instantly share code, notes, and snippets.

@mdmitry1
Last active February 4, 2025 20:15
Show Gist options
  • Save mdmitry1/0fffca2838aaea5d759d0a9ac1353111 to your computer and use it in GitHub Desktop.
Save mdmitry1/0fffca2838aaea5d759d0a9ac1353111 to your computer and use it in GitHub Desktop.
Disjoint set
#!/usr/bin/python3
'''
https://stackoverflow.com/questions/20154368/union-find-implementation-using-python
'''
def union_find(lis):
lis = map(set, lis)
unions = []
for item in lis:
temp = []
for s in unions:
if not s.isdisjoint(item):
item = s.union(item)
else:
temp.append(s)
temp.append(item)
unions = temp
return unions
if __name__ == '__main__':
l = []
l.append(["1", "2"])
l.append(["2", "3"])
l.append(["4", "5"])
l.append(["6", "7"])
l.append(["1", "7"])
ds=union_find(l)
for i in range(0,len(ds)):
tmp_list=list(ds[i])
tmp_list.sort()
print(i,":",tmp_list)
# distutils: language=c++
'''
https://stackoverflow.com/questions/20154368/union-find-implementation-using-python
'''
def union_find(lis):
lis = map(set, lis)
unions = []
for item in lis:
temp = []
for s in unions:
if not s.isdisjoint(item):
item = s.union(item)
else:
temp.append(s)
temp.append(item)
unions = temp
return unions
#!/usr/bin/tcsh -f
"/bin/true" '''\'
setenv PYTHONPATH `realpath $0 | xargs dirname`
exec python3.13 $0 $*
'''
from disjoint_set_c import union_find
l = []
l.append(["1", "2"])
l.append(["2", "3"])
l.append(["4", "5"])
l.append(["6", "7"])
l.append(["1", "7"])
ds=union_find(l)
for i in range(0,len(ds)):
tmp_list=list(ds[i])
tmp_list.sort()
print(i,":",tmp_list)
#!/usr/bin/python3.13
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("disjoint_set_c.pyx", language_level=3)
)
MODULE=disjoint_set_c
VER=13
EXT=cpython-3$(VER)-$(HOSTTYPE)-gnu.so
SO=$(MODULE).$(EXT)
%.$(EXT): %_setup.py %.pyx
python3.$(VER) $< build_ext -i
strip $@
-rm -rf build
all: $(SO)
clean:
-rm -rf $(SO) $(MODULE).cpp
#!/usr/bin/tcsh -f
make clean all
disjoint_set.py | sum
disjoint_set_c_run.py | sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment