Algorithm/이것이 코딩테스트다

[이.코.테] 주요 라이브러리

hammii 2021. 9. 12. 22:44
728x90
반응형

내장 함수

  • sum
result = sum([1,2,3,4,5])	# 15
  • min
result = min(7,3,5,2)	# 2
  • max
result = max(7,3,5,2)	# 7
  • eval
result = eval("(3+5) * 7")	# 56
  • sorted
result = sorted([9,1,8,5,4])	# [1,4,5,8,9]
result = sorted([9,1,8,5,4], reverse=True)	# [9,8,5,4,1]

result = sorted([('홍길동', 35), ('이순신', 75), ('아무개', 50)], key=lambda x: x[1], reverse=True)	# [('이순신', 75), ('아무개', 50), ('홍길동', 35)]
  • sort - 내부 값이 바로 변경됨
data = [9,1,8,5,4] 
data.sort()	# [1,4,5,8,9]

 

itertools

  • permutations
from itertools import permutations

result = list(permutations(data, 3))	# 3개 뽑는 모든 순열
  • combinations
from itertools import combinations

result = list(combinations(data, 2))	# 2개 뽑는 모든 조합
  • product - 중복 포함 permutations
from itertools import product

result = list(product(data, repeat=2))	# 2개 뽑는 모든 순열 (중복 포함)
  • combinations_with_replacement - 중복 포함 combinations
from itertools import combinations_with_replacement

result = list(combinations_with_replacement(data, repeat=2)) # 2개 뽑는 모든 조합 (중복 포함)

 

heapq

  • 우선순위 큐 기능을 구현할 때
  • 시간 복잡도: 
import heapq

heap.heappush(리스트, value) # 오름차순
heap.heappop(리스트)

heap.heappush(리스트, -value) # 내림차순
heap.heappop(리스트)

 

bisect

  • left_value ≤ x ≤ right_value 원소의 개수 구하기
  • 시간 복잡도: 
from bisect import bisect_left, bisect_right

def count_by_range(a, left_value, right_value):
	right_index = bisect_right(a, right_value)
	left_index = bisect_left(a, left_value)
	return right_index - left_index

 

collections

  • deque
    • 인덱싱과 슬라이싱 불가
    • 데이터 삽입, 삭제: 
from collections import deque

data.appendleft(x)
data.append(x)
data.popleft()
data.pop()
  • Counter
from collections import Counter

counter = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])

counter['red']	# 2
counter['blue']	# 3
counter['green'] # 1
dict(counter)	# {'red': 2, 'blue': 3, 'green': 1}

 

math

  • factorial
import math

math.factorial(5)	# 120
  • sqrt
import math

math.sqrt(7)	# 2.645751...
  • gcd
import math

math.gcd(21, 14)	# 7
  • pi & 자연상수 e
import math

math.pi # 3.141592...
math.e # 2.718281...

 

 

728x90
반응형