Skip to content

Instantly share code, notes, and snippets.

@chairco
Created May 25, 2019 14:29
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 chairco/db94600401c99a865b0c552ef84f8c5c to your computer and use it in GitHub Desktop.
Save chairco/db94600401c99a865b0c552ef84f8c5c to your computer and use it in GitHub Desktop.
無聊看到題目就來寫
def findmygroup(g, head=0, group=None):
"""recursive find friend
"""
global groups
if group is None:
group = []
else:
group = list(group)
if not g:
groups.append(group)
return
elif head in group:
groups.append(group)
ptr = list(g.keys())[0]
return findmygroup(g, ptr)
else:
ptr = g.get(head, None)
if ptr is not None:
del g[head]
group.append(head)
return findmygroup(g, ptr, group)
g = {idx: value for idx, value in enumerate([4, 7, 2, 9, 6, 0, 8, 1, 5, 3])} # 輸入
groups = [] # 存結果
findmygroup(g=g)
print(groups) # 印出結果
@chairco
Copy link
Author

chairco commented May 25, 2019

https://github.com/AlexTrinityBlock/APCS
大意就是假如有10個人,他們最多一位好友,關係是透過 index 來連結 : [4, 7, 2, 9, 6, 0, 8, 1, 5, 3] �-> 0:4, 1:7, 2:2, 3:9, 4:6, 5:0, 6:8, 7:1, 8:5, 9:3 這樣
然後 0,4,6,8,5 彼此形成一個環所以是一群,2:2 自己和自己是朋友,3, 9 自成一群,反正就是給個串列找群。就遞迴解,頗無聊... 對,會無聊浪費時間寫的人大概就只有我吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment