ss = [0,1,2,3,4,5,6,7,8,9]
f = [4, 7, 2, 9, 6, 0, 8, 1, 5, 3]
# 1:找到第一群'
# g = []
# cur = 0
# while cur not in g:
# g.append(cur)
# cur = f[cur]
# print(g)
# 2:'找到每一群'
# for s in ss:
# g = []
# cur = s
# while cur not in g:
# g.append(cur)
# cur = f[cur]
# print(g)
# 3: '找到每一群,去重覆群'
# v = []
# for s in ss:
# g = []
# cur = s
# if s not in v:
# while cur not in g:
# g.append(cur)
# v.append(cur)
# cur = f[cur]
# print(g)
# 4: '找到每一群,去重覆群,算出共幾群'
v = []
gs = []
for s in ss:
g = []
cur = s
if s not in v:
while cur not in g:
g.append(cur)
v.append(cur)
cur = f[cur]
print(g)
gs.append(g)
print('共',len(gs),'群')
Output:
[0, 4, 6, 8, 5]
[1, 7]
[2]
[3, 9]
共 4 群
沒有留言:
張貼留言