[알고리즘] 이코테 1단계 내용정리(주요 라이브러리)

SeHoony·2022년 3월 8일
1

알고리즘

목록 보기
3/11
post-thumbnail

주요 내용 요약
1. 내장함수(sum([]), min(,,,), max(,,,), eval(""), sorted())
2. itertools(permutations, combinations, product, combinations_with_replacement)
3. heapq(heapq.heappush(heap, value), heapq.heappop(heap)) : 오름차순
4. bisect(bisect_left(arr, 4), bisect_right(arr, 4)) : 정렬된 배열에서 특정 원소 찾기
5. collections(deque, Counter)
6. math(factorial, sqrt, gcd, pi, e)
: 'import math'만 하고 math.factorial(x) 이런 식으로 가져다 씀

1. 내장함수

  • sum([1,2,3,4]) -> int
  • min(2,3,4) -> int
  • max(2,3,4) -> int
  • eval("(3+5)*7") -> int
  • sorted([4,6,3,1,7]) -> array
    : attribute 1(reverse): ex> sorted([4,6,3,1,7], reverse=True) -> array
    : attribute 2(key) : ex> sorted([('강세훈',28), ('강기훈', 32), ('용팔이', 40)], key= lambda x: x[1], reverse=True)

2. itertools

  • 종류 : permutations(순열), combinations(조합), product(중복순열), combinations_with_replacement(중복조합)
  • permutations(순열)
    : 리스트에서 r개 데이터를 뽑아 나열할 수 있는 모든 경우의 수(순서 고려!)
from itertools import permutations
data = ['A', 'B', 'C']
result = list(permutations(data,3))
print(result)
=> [('A','B','C'),('A','C','B'), ('B','A','C'), ... ]
  • combinations(조합)
    : 리스트에서 r개 데이터를 뽑아 순서 고려없이 나열할 수 있는 모든 경우의 수(순서 고려 X!)
from itertools import combinations
data = ['A', 'B', 'C']
result = list(combinations(data,3))
print(result)
=> [('A','B','C')]
  • product(중복순열)
    : 리스트에서 r개 데이터를 뽑아 중복하여 나열할 수 있는 모든 경우의 수(순서 고려! 중복 가능!)
from itertools import product
data = ['A', 'B', 'C']
result = list(product(data,repeat=2))
print(result)
=> [('A','A'), ('A','B'), ('A','C'), ('B','A'),...]
  • combinations_with_replacement(중복조합)
    : 리스트에서 r개 데이터를 뽑아 중복하여 순서 고려없이 나열할 수 있는 모든 경우의 수(순서 고려X! 중복 가능!)
from itertools import combinations_with_replacement
data = ['A', 'B', 'C']
result = list(combinations_with_replacement(data,2))
print(result)
=> [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C') , ('C', 'C')]

3. heapq

  • 우선순위 큐 기능 구현을 위해 제공
  • 파이썬의 힙은 최소 힙(Min Heap)으로 구성
  • 모든 원소를 힙에 넣었다가 빼는 것만으로 '오름차순' 구현
  • 관련 메서드
    : heapq.heappush(h, value)
    : heapq.heappop(h)
import heapq

arr = [2,5,1,7,3,9]
heap = []
result = []

for item in arr:
  heapq.heappush(heap, item)

for i in range(len(heap)):
  result.append(heapq.heappop(heap))
print(result)

4. bisect

  • 이진탐색 구현
  • 정렬된 배열에서 특정 원소 찾기
  • 시간 복잡도 : O(log(N))
  • 관련 메서드
    : bisect_left(arr,4) -> index : (정렬된 순서 유지하면서, 4를 삽입할 가장 왼쪽 인덱스 리턴)
    : bisect_right(arr,4) -> index
from bisect import bisect_left, bisect_right

arr = [1,2,4,6,8]
print(bisect_left(arr,4))
print(bisect_right(arr,4))
=> 2, 3

5. collections

  • deque, Counter 주로 사용
  • deque
    • 파이썬에서는 deque를 이용해 '큐' 구현
    • 일반 리스트는 뒤쪽에서 삽입, 제거할 때는 O(1)이지만, 앞쪽에 삽입, 제거 시 O(N)이다.
    • deque는 앞이든 뒤든 시간 복잡도가 O(1)
    • 관련 메서드
      : append(), appendleft(), pop(), popleft()
  • Counter
    • 등장횟수를 세는 기능 제공

      from collections import Counter
      
      counter = Counter(['red', 'red' , 'red', 'yellow', 'green', 'blue', 'blue'])
      print(counter['red'])
      print(dict(counter))    

6. math

  • 관련 메서드
    : factorial(x) = x!
    : sqrt(x) = x의 제곱근을 실수형으로 반환
    : gcd(a,b) = a,b의 최대공약수
import math
print(math.factorial(5))
print(math.sqrt(36))
print(math.gcd(72,36))
profile
두 발로 매일 정진하는 두발자, 강세훈입니다. 저는 '두 발'이라는 이 단어를 참 좋아합니다. 이 말이 주는 건강, 정직 그리고 성실의 느낌이 제가 주는 분위기가 되었으면 좋겠습니다.

0개의 댓글