Skip to content

Instantly share code, notes, and snippets.

@bityob
Last active July 19, 2017 15:22
Show Gist options
  • Select an option

  • Save bityob/2a6ef88062e4be892a65dbb0ce681441 to your computer and use it in GitHub Desktop.

Select an option

Save bityob/2a6ef88062e4be892a65dbb0ce681441 to your computer and use it in GitHub Desktop.
find_union_algo created by bityob - https://repl.it/J8x7/7
indata = """1 2
3 4
5 6
7 8
7 9
2 8
0 6
1 9"""
data = [x.split() for x in indata.splitlines()]
connections = []
def add_conn(newconn):
isexists = False
for conn in connections:
if any(x in conn for x in newconn):
conn.add(newconn[0])
conn.add(newconn[1])
isexists = True
for conn1 in connections:
for conn2 in connections:
if (conn1 != conn2) and len(conn1 & conn2) > 0:
connections.append(conn1 | conn2)
connections.remove(conn1)
connections.remove(conn2)
if not isexists:
connections.append(set(newconn))
print(f"\t{connections}")
for newconn in data:
print(newconn)
add_conn(newconn)
print(connections) #[{'4', '3'}, {'6', '5', '0'}, {'8', '7', '1', '2', '9'}]
# output:
# ['1', '2']
# [{'2', '1'}]
# ['3', '4']
# [{'2', '1'}, {'4', '3'}]
# ['5', '6']
# [{'2', '1'}, {'4', '3'}, {'6', '5'}]
# ['7', '8']
# [{'2', '1'}, {'4', '3'}, {'6', '5'}, {'8', '7'}]
# ['7', '9']
# [{'2', '1'}, {'4', '3'}, {'6', '5'}, {'9', '8', '7'}]
# ['2', '8']
# [{'4', '3'}, {'6', '5'}, {'8', '7', '1', '2', '9'}]
# ['0', '6']
# [{'4', '3'}, {'6', '5', '0'}, {'8', '7', '1', '2', '9'}]
# ['1', '9']
# [{'4', '3'}, {'6', '5', '0'}, {'8', '7', '1', '2', '9'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment