Search
Duplicate

코테 주요 라이브러리

Created
2023/10/10 10:26
Tags

코테 주요 라이브러리

내장함수

# 합 sum([1, 2, 3]) # 6 # 최소값 min(1, 2, 3) # 1 # 최대값 max(1, 2, 3) # 3 # 문자열 > 수식 eval("3+5") # 8 # key 정렬 sorted([('에이', 5), ('비', 1), ('씨', 2)], key = lambda x: x[1]) # [('비'), 1), ('씨', 2), ('에이', 5)]
Python
복사

itertools - 순열, 조합

# 순열 from itertools import permutations a = ['A', 'B', 'C'] res = list(permutations(a, 3)) print(res) # [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')] # 조합 from itertools import combinations a = ['A', 'B', 'C'] res = list(combinations(a, 2)) print(res) # [('A', 'B'), ('A', 'C'), ('B', 'C')] # 중복순열 from itertools import product a = ['A', 'B', 'C'] res = list(product(a, repeat = 2)) print(res) # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')] # 중복조합 from itertools import combinations_with_replacement a = ['A', 'B', 'C'] res = list(combinations_with_replacement(a, 2)) print(res) # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
Python
복사

heapq - 힙, 우선순위큐

파이썬의 힙은 최소힙으로 구성되어 있어서, 원소 전체를 힙에 넣었다 빼는 것으로 오름차순 정렬이 완료된다 (O(NlogN))
# 추가 heapq.heappush() # 제거 heapq.heappop() # 정렬 import heapq def heapsort(iterable): h = [] res = [] for value in iterable: heapq.heappush(h, value) # (h, -value) for i in range(len(h)): res.append(heapq.heappop(h)) # (-heapq.heappop(h)) return res res = heapsort([1, 3, 5, 7, 9, 2, 4, 6]) print(res) # [1, 2, 3, 4, 5, 6, 7, 9]
Python
복사

bisect - 이진탐색

이진탐색 / 정렬된 배열에서 효과적으로 사용 가능
배열 a에서 각각 왼쪽과 오른쪽에서 삽입할 원소 x의 인덱스를 찾는 함수
bisect_left(a, x) bisect_right(a, x)
Python
복사

collections - 덱, 카운터

덱(deque) - 인덱싱, 슬라이싱 불가능 / 데이터의 시작과 끝 부분 데이터 추가 / 삭제가 용이
from collections import deque data = deque([2, 3, 4]) data.appendleft(1) data.append(5) print(data) # deque([1, 2, 3, 4, 5])
Python
복사
카운터(counter) - 개수
from collections import Counter counter = Counter(['red', 'blue', 'green', 'blue']) print(counter['blue']) # 2 print(dict(counter)) # {'red': 1, 'blue': 2, 'green': 1}
Python
복사

math - 팩토리얼, 제곱근, GCD, 삼각함수, 수학상수

import math print(math.factorial(5)) # 120 print(math.sqrt(4)) # 2.0 print(math.gcd(25, 15)) # 5
Python
복사