PromleeBlog
sitemap
aboutMe

posting thumbnail
파이썬 외부 자료구조 라이브러리 정리
Python External Data Structures Libraries

📅

🚀

collections 🔗

파이썬의
collections
모듈은 내장 자료구조를 보완하는 다양한 클래스들을 제공합니다.

deque 🔗

deque (Double-Ended Queue)는 양쪽 끝에서 빠르게 데이터를 추가하거나 제거할 수 있는 자료구조입니다. 일반적으로 큐(Queue)나 스택(Stack)을 구현할 때 유용합니다.
from collections import deque
 
 # 양쪽 끝에서 데이터를 추가하고 제거할 수 있는 deque 예제
d = deque(["a", "b", "c"])
d.append("d")         # 오른쪽에 추가
d.appendleft("z")     # 왼쪽에 추가
print("Deque:", d)    # 결과: deque(['z', 'a', 'b', 'c', 'd'])
 
d.pop()               # 오른쪽에서 제거
d.popleft()           # 왼쪽에서 제거
print("Modified deque:", d)  # 결과: deque(['a', 'b', 'c'])

Counter 🔗

Counter는 데이터가 몇 번 나타나는지를 세어주는 도구입니다. 아래 예제는 문자열에서 각 글자의 등장 횟수를 세는 방법을 보여줍니다.
from collections import Counter
 
 # 문자열에서 각 글자의 등장 횟수를 세기
text = "apple"
count = Counter(text)
print("Letter count:", count)  # 결과: Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})

defaultdict 🔗

defaultdict는 없는 키에 접근할 때 기본값을 자동으로 생성해주는 딕셔너리입니다.
from collections import defaultdict
 
 # 기본 값이 0인 딕셔너리 생성
dd = defaultdict(int)
dd["apple"] += 1
dd["banana"] += 2
print("defaultdict:", dict(dd))  # 결과: {'apple': 1, 'banana': 2}

🚀

heapq 🔗

heapq
모듈은 최소 힙(Min Heap) 자료구조를 제공합니다. 최소 힙은 가장 작은 값을 빠르게 찾을 수 있어서 우선순위 큐(또는 작업 스케줄링) 문제에 유용합니다.

최소 힙(Min Heap) 구현 🔗

heapq 모듈을 사용하면 리스트를 최소 힙(Min Heap)으로 변환하고, 가장 작은 값을 빠르게 찾을 수 있습니다.
import heapq
 
 # 리스트를 최소 힙으로 변환
heap = [5, 1, 3, 7, 2]
heapq.heapify(heap)
print("Heapified list:", heap)  # 결과: [1, 2, 3, 7, 5]
 
 # 가장 작은 값을 꺼내기
smallest = heapq.heappop(heap)
print("Smallest element:", smallest)  # 결과: 1
print("Heap after pop:", heap)
 
 # 새로운 값을 힙에 추가하기
heapq.heappush(heap, 0)
print("Heap after push:", heap)  # 결과: [0, 2, 3, 7, 5]

max heap 구현 🔗

heapq 모듈은 최소 힙(Min Heap)만 지원하므로, 최대 힙(Max Heap)을 구현하려면 음수로 변환하여 사용해야 합니다.
import heapq
 
 # 리스트를 최대 힙으로 변환
heap = [5, 1, 3, 7, 2]
heap = [-x for x in heap]
heapq.heapify(heap)
print("Max heap:", [-x for x in heap])  # 결과: [7, 5, 3, 1, 2]
 
 # 가장 큰 값을 꺼내기
largest = -heapq.heappop(heap)
print("Largest element:", largest)  # 결과: 7
print("Heap after pop:", [-x for x in heap])
 
 # 새로운 값을 힙에 추가하기
heapq.heappush(heap, -4)
print("Heap after push:", [-x for x in heap])  # 결과: [5, 4, 3, 1, 2]

🚀

bisect 🔗

bisect 모듈은 정렬된 리스트에서 이진 검색(binary search)을 수행하여, 데이터를 빠르게 삽입할 위치를 찾을 수 있게 도와줍니다.
이진 탐색 트리, 이분 탐색 자료구조를 대체할 수 있습니다.
import bisect
 
 # 이미 정렬된 리스트
sorted_list = [1, 3, 4, 7, 9]
 
 # 값 5 가 들어갈 적절한 위치 찾기
position = bisect.bisect_left(sorted_list, 5)
print("Insertion point for 5:", position)  # 결과: 3
 
 # 데이터를 삽입하면 정렬된 상태 유지하기
bisect.insort_left(sorted_list, 5)
print("List after insertion:", sorted_list)  # 결과: [1, 3, 4, 5, 7, 9]

🚀

itertools 🔗

itertools 모듈은 반복자(iterator)를 만들어주는 도구들을 제공합니다. 이를 사용하면 반복문을 작성할 때 코드를 간결하게 만들 수 있습니다.
쉽게 생각해서
조합
은 (1, 2) 와 (2, 1) 을 같은 것으로 보고
순열
은 (1, 2) 와 (2, 1) 을 다른 것으로 보는 것입니다.
import itertools
 
list1 = [1, 2, 3]
 
 # 조합(Combination)
combinations = itertools.combinations(list1, 2) # 2개의 요소로 이루어진 모든 조합
print("Combinations:", list(combinations))  # 결과: [(1, 2), (1, 3), (2, 3)]
 
 # 순열(Permutation)
permutations = itertools.permutations(list1, 2) # 2개의 요소로 이루어진 모든 순열
print("Permutations:", list(permutations))  # 결과: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
 
 # 중복 조합(Combination with replacement)
combinations_with_replacement = itertools.combinations_with_replacement(list1, 2) # 2개의 요소로 이루어진 중복 조합
print("Combinations with replacement:", list(combinations_with_replacement))  # 결과: [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
 
 # 중복 순열(Permutation with replacement)
permutations_with_replacement = itertools.product(list1, repeat=2) # 2개의 요소로 이루어진 중복 순열
print("Permutations with replacement:", list(permutations_with_replacement))  # 결과: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
 
 # 두 리스트의 모든 조합 구하기
list1 = [1, 2]
list2 = ["a", "b"]
 
combinations = itertools.product(list1, list2)
print("All combinations:", list(combinations))  # 결과: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

🚀

참고 🔗