def drop_cycle(edge, max_length=20):
"""
删除列表中形成的小闭环
@edge: 原始顶点id
@max_length: 容许闭环的最小长度
return: 输出删除小闭环后的列表
"""
drop_list = []
drop_count = 0
for i, item in enumerate(edge):
if item not in drop_list:
drop_list.append(item)
else:
last_index = len(drop_list) - 1 - drop_list[::-1].index(item)
if i - last_index - drop_count < max_length:
drop_count += len(drop_list[last_index:])
drop_list = drop_list[:last_index+1]
else:
drop_list.append(item)
# 去掉首尾构成的闭环 如: [956 1035 1538 ...... 2028 1035 952 956] ==> 1035->952->956->1035
circle_count = np.where(np.bincount(drop_list) >= 2)[0]
for item in circle_count:
if item == drop_list[0]:
continue
first_id = drop_list.index(item)
last_id = drop_list[::-1].index(item)
if first_id + last_id <= max_length:
length = len(drop_list)
drop_list = drop_list[first_id:length-last_id]
return edge
Test
a = [2, 3, 1, 2, 5, 8, 1, 6, 1, 2, 1, 3, 4, 1, 2]
print(drop_cycle(a, 3)) # [2 3 1 2 5 8 1 3 4 1 2]