Skip to content

Instantly share code, notes, and snippets.

@metruzanca
Forked from seanhuggins1/friendGroups.py
Last active November 24, 2020 13:52
Show Gist options
  • Save metruzanca/b78c1a05f2b18cd14814cd996b67f39d to your computer and use it in GitHub Desktop.
Save metruzanca/b78c1a05f2b18cd14814cd996b67f39d to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.0-final"
},
"orig_nbformat": 2,
"kernelspec": {
"name": "python3",
"display_name": "Python 3.9.0 64-bit",
"metadata": {
"interpreter": {
"hash": "ac2eaa0ea0ebeafcc7822e65e46aa9d4f966f30b695406963e145ea4a91cd4fc"
}
}
}
},
"nbformat": 4,
"nbformat_minor": 2,
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['0', '1', '5', '2']\n['3', '6']\n['4']\n"
]
}
],
"source": [
"\n",
"def dfs(visited, graph, node):\n",
" if node not in visited:\n",
" yield node\n",
" visited.add(node)\n",
" for neighbor in graph[node]:\n",
" yield from dfs(visited, graph, neighbor)\n",
"\n",
"def printFriendGroups(graph):\n",
" visited = set()\n",
" while (len(graph) > 0):\n",
" friendGroup = []\n",
" graphCopy = graph.copy()\n",
" for node in dfs(visited, graphCopy, list(graph.keys())[0] ):\n",
" friendGroup.append(node)\n",
" graph.pop(node)\n",
" print(friendGroup)\n",
"\n",
"\n",
"\n",
"graph = {\n",
" '0':['1','2'],\n",
" '1':['0','5'],\n",
" '2':['0'],\n",
" '3':['6'],\n",
" '4':[],\n",
" '5':['1'],\n",
" '6':['3'],\n",
" }\n",
"printFriendGroups(graph)"
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment