Skip to content

Instantly share code, notes, and snippets.

@whusnoopy
Created September 3, 2021 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whusnoopy/c9b43dde396aa57f61318c09870d5517 to your computer and use it in GitHub Desktop.
Save whusnoopy/c9b43dde396aa57f61318c09870d5517 to your computer and use it in GitHub Desktop.
disjoint_set example for https://www.v2ex.com/t/799577
input = [
{'A': 'A1'},
{'A1': 'A2'},
{'A3': 'A4'},
{'A2': 'A3'},
{'B4': 'B3'},
{'B1': 'B4'},
{'B4': 'B'},
{'B3': 'B2'},
{'B2': 'B5'},
]
dset = {}
output = {}
def find(k):
if k not in dset:
dset[k] = k
elif dset[k] != k:
dset[k] = find(dset[k])
return dset[k]
for pairs in input:
for (k, v) in pairs.items():
vp = find(v)
dset[vp] = find(k)
print(dset)
for pairs in input:
for (k, v) in pairs.items():
kp = find(k)
if kp not in output:
output[kp] = set()
output[kp].add(k)
output[kp].add(v)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment