본문 바로가기
코딩테스트

[코딩테스트] 코딩테스트를 위한 Python 모듈과 패키지

by cogito21_python 2024. 6. 3.
반응형

1. collections

  • 주요 기능:
    • deque: 양방향 큐를 지원하는 자료구조로, 스택과 큐의 효율적인 연산을 제공합니다.
    • Counter: 해시 가능한 객체의 개수를 셀 때 유용합니다.
    • defaultdict: 기본 값을 설정할 수 있는 딕셔너리로, 키가 존재하지 않을 때 기본 값을 자동으로 제공합니다.
    • namedtuple: 필드 이름을 가진 튜플로, 튜플의 인덱스 접근을 더 이해하기 쉽게 만들어줍니다.

2. heapq

  • 주요 기능:
    • 힙 큐 알고리즘을 제공하여 우선순위 큐를 구현할 때 사용됩니다.
    • 최소 힙과 최대 힙을 통해 가장 작은/큰 요소를 효율적으로 추출할 수 있습니다.

3. itertools

  • 주요 기능:
    • 반복자 생성 함수들을 제공하여 효율적인 반복 작업을 지원합니다.
    • product, permutations, combinations, combinations_with_replacement 등 다양한 조합과 순열을 생성할 수 있습니다.

4. functools

  • 주요 기능:
    • 고차 함수 (다른 함수들을 다루는 함수)를 제공하며, lru_cache를 통해 함수 결과를 캐싱하여 성능을 개선할 수 있습니다.
    • reduce 함수는 누적 연산을 수행할 때 사용됩니다.

5. bisect

  • 주요 기능:
    • 정렬된 리스트를 이진 탐색하는 기능을 제공하여 삽입 위치를 효율적으로 찾을 수 있습니다.
    • bisect_left와 bisect_right를 사용하여 리스트에 값을 삽입할 때 유용합니다.

6. math

  • 주요 기능:
    • 수학적 연산을 위한 다양한 함수들을 제공합니다.
    • gcd, lcm, factorial, sqrt, ceil, floor, log 등 다양한 수학적 함수가 포함되어 있습니다.

7. random

  • 주요 기능:
    • 난수 생성 및 무작위 선택 기능을 제공합니다.
    • randint, choice, shuffle, sample 등을 사용하여 무작위 데이터를 생성할 수 있습니다.

8. time 및 datetime

  • 주요 기능:
    • 시간과 날짜를 다루기 위한 다양한 함수들을 제공합니다.
    • time.time(), time.sleep(), datetime.datetime, datetime.timedelta 등을 사용하여 시간 측정 및 조작을 할 수 있습니다.

9. re

  • 주요 기능:
    • 정규 표현식을 사용하여 문자열 검색과 조작을 할 수 있습니다.
    • re.match, re.search, re.findall, re.sub 등을 사용하여 문자열 패턴을 처리할 수 있습니다.

10. operator

  • 주요 기능:
    • 함수형 프로그래밍을 위한 연산자 함수들을 제공합니다.
    • operator.itemgetter, operator.attrgetter, operator.methodcaller 등을 사용하여 정렬이나 데이터 추출 시 유용합니다.

1. collections 모듈

deque

from collections import deque

# 양방향 큐 생성
dq = deque([1, 2, 3, 4, 5])
dq.append(6)
dq.appendleft(0)
print(dq)  # deque([0, 1, 2, 3, 4, 5, 6])

dq.pop()
dq.popleft()
print(dq)  # deque([1, 2, 3, 4, 5])

 

Counter

from collections import Counter

# 문자열의 각 문자의 개수를 셉니다.
counter = Counter('hello world')
print(counter)  # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

 

defaultdict

from collections import defaultdict

# 기본 값을 제공하는 딕셔너리 생성
dd = defaultdict(int)
dd['a'] += 1
print(dd)  # defaultdict(<class 'int'>, {'a': 1})

 

namedtuple

from collections import namedtuple

# namedtuple 생성
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)
print(p)  # Point(x=11, y=22)
print(p.x, p.y)  # 11 22

 

2. heapq 모듈

import heapq

# 리스트를 힙으로 변환
heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(heap)
print(heap)  # [0, 1, 4, 3, 9, 2, 5, 7, 8, 6]

# 힙에 요소 추가
heapq.heappush(heap, -5)
print(heap)  # [-5, 0, 4, 3, 1, 2, 5, 7, 8, 6, 9]

# 힙에서 최소값 제거 및 반환
print(heapq.heappop(heap))  # -5
print(heap)  # [0, 1, 4, 3, 6, 2, 5, 7, 8, 9]

 

3. itertools 모듈

product

from itertools import product

# 데카르트 곱
print(list(product([1, 2], ['a', 'b'])))  # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

 

permutations

from itertools import permutations

# 순열
print(list(permutations([1, 2, 3], 2)))  # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

 

combinations

from itertools import combinations

# 조합
print(list(combinations([1, 2, 3], 2)))  # [(1, 2), (1, 3), (2, 3)]

 

4. functools 모듈

lru_cache

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print([fibonacci(n) for n in range(10)])  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

 

5. bisect 모듈

import bisect

# 정렬된 리스트에 삽입할 위치 찾기
arr = [1, 3, 4, 4, 4, 6, 7]
print(bisect.bisect_left(arr, 4))  # 2
print(bisect.bisect_right(arr, 4))  # 5

# 정렬된 리스트에 값 삽입
bisect.insort(arr, 5)
print(arr)  # [1, 3, 4, 4, 4, 5, 6, 7]

 

6. math 모듈

import math

print(math.gcd(60, 48))  # 12
print(math.factorial(5))  # 120
print(math.sqrt(16))  # 4.0

 

7. random 모듈

import random

print(random.randint(1, 10))  # 1부터 10까지 임의의 정수
print(random.choice(['apple', 'banana', 'cherry']))  # 리스트에서 임의의 요소 선택
print(random.sample(range(100), 5))  # 0부터 99까지의 범위에서 5개의 임의의 숫자 선택

 

8. time 및 datetime 모듈

time

import time

start_time = time.time()
# some code
end_time = time.time()
print(f"Elapsed time: {end_time - start_time} seconds")

 

datetime

from datetime import datetime, timedelta

now = datetime.now()
print(now)  # 현재 시간 출력

future = now + timedelta(days=5)
print(future)  # 현재 시간으로부터 5일 후

 

9. re 모듈

import re

pattern = re.compile(r'\d+')
print(pattern.findall('There are 123 apples and 456 oranges'))  # ['123', '456']

# 문자열 치환
print(re.sub(r'apples', 'bananas', 'I like apples'))  # I like bananas

 

10. operator 모듈

import operator

# itemgetter를 사용한 정렬
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
students.sort(key=operator.itemgetter(2))
print(students)  # [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

 

 

반응형