카테고리 없음
공간이 연속 할 경우 합치기
virbr0.net
2024. 1. 22. 00:18
한쌍의 시작점, 끝점 목록과 이 목록에 추가할 한쌍의 시작점, 끝점이 주어질때,
이를 직선 상에서 연속 될 경우, 하나로 묶는 방법이다.
예를 들어,
(1, 5), (8, 10) 과 새로 추가할 점으로 (6, 7) 이 주어진다면,
(1, 10) 으로 반환한다.
이를 표현하는 코드를 작성하면, 아래와 같다.
from bisect import bisect_left
def find_connected_lists(point_list, new_point):
# 새로 들어온 순서 쌍을 배치할 위치를 찾는다.
idx = bisect_left(point_list, new_point)
l_merge = False
r_merge = False
# 앞쪽을 합쳐야 되면 l_merge 를 True 로
if new_point[0] - point_list[idx-1][1] == 1:
l_merge = True
# 뒷쪽을 합쳐야 되면 r_merge 를 True 로
if point_list[idx][0] - new_point[1] == 1:
r_merge = True
# 앞쪽만 합쳐야 할때
if l_merge == True and r_merge == False:
point_list[idx - 1][1] = new_point[1]
# 뒷쪽만 합쳐야 할때
elif l_merge == False and r_merge == True:
point_list[idx][0] = new_point[0]
# 양쪽 다 합쳐야 할때
elif l_merge == True and r_merge == True:
point_list[idx - 1][1] = point_list[idx][1]
# 앞쪽으로 합친 후 뒷쪽 삭제
point_list.pop(idx)
# 아무것도 아니라 중간에 추가해야 할때
else:
point_list.insert(idx, new_point)
return point_list
point_list = [[1, 5], [6, 6], [7, 7], [20, 25]]
point_list.sort()
new_point = [9, 19]
print(find_connected_lists(point_list, new_point))
위 코드는 주로, 파일 시스템, 메모장 칸 등에서 삭제 되면서 하나의 공간으로 다시 합칠 필요가 있을 때 사용하면 된다.