Back-End/Python

[Python] 코테 - 반드시 알아야 할 라이브러리 6가지

uni2237 2021. 3. 11.
728x90
728x90

📌 1. 내장함수 

 

1. sum()

  리스트와 같은 iterable 객체의 모든 원소의 합 반환

result = sum( [1, 2, 3, 4, 5] )
print(result) => 15

2. min(), max()

   min(): 파라미터 2개 이상 들어왔을 때 가장 작은 값 반환

   max():                   //                    가장 큰 값 반환

result = min(7, 3, 6, 1)
print(result) => 1

max = min(7, 3, 6, 1)
print(result) => 7

3. eval()

  수학 수식(문자열 형태) 계산 결과 반환

result = eval("(3+5) * 7")
print(result) => 56

4. sorted()

  iterable 객체 들어왔을 때 정렬된 결과 반환

result = sorted([4, 7, 3, 1])  # 오름 차순
print(result) => [1,3,4,7]
result = sorted([4, 7, 3, 1], reverse = True) # 내림차순
print(result) => [7,4,3,1]

key 속성으로 기준 정할 수 있음 

result = sorted( [ ('a', 40), ('b', 70), ('c', 20) ] , key = lambda x : x[1], reverse = True)
print(result) => [ ('b', 70), ('a', 40) ,('c', 20) ]
# x[1] 을 기준으로 했으므로 숫자들 기준으로 내림차순 정렬됨

+ sort()

리스트와 같은 iterable 객체는 기본적으로 sort() 함수 내장!

굳이 sorted() 안 써도 됨 => 리스트 값이 정렬된 것으로 바로 바뀜

data = [3, 1, 2]
data.sort()
print(data) => [1, 2, 3]

 

 


📌 2. itertools - 반복되는 데이터 처리!

 

1. permutations

리스트 같은 iterable 객체에서 r개의 데이터를 뽑아 일렬로 나열하는 모든 경우(순열)제시

클래스이므로 객체 초기화 후 리스트 자료형으로 변환 해야함.

from itertools import permutations
data = ['A', 'B', 'C']
result = list(permutations(data, 3)) # 데이터중 3개를 뽑아 나열(순열)
print(result) => [('A', 'B' ,'C'),('A', 'C', 'B'), ,,,,,,,, , ('C', 'B', 'A')]

2. combinations

리스트 같은 iterable 객체에서 r개의 데이터를 뽑아 순서없이 일렬로 나열하는 모든 경우(조합)제시

클래스이므로 객체 초기화 후 리스트 자료형으로 변환 해야함.

from itertools import combinations

data = ['A', 'B', 'C']

result = list(combinations(data, 2)) # 데이터중 2개를 뽑아 순서없이 나열(조합)

print(result) => [('A', 'B'), ('A', 'C'),  ('B', 'C')]

3. product

permutations에서 원소 중복, 뽑고자 하는 데이터 수를 repeat 속성값으로 넣음

from itertools import product

data = ['A', 'B', 'C']

result = list(product(data, repeat=2)) # 데이터중 2개를 뽑아 나열(중복 순열)

print(result) => [('A', 'A'),('A', 'B'), ,,,,,,,, , ('C', 'C')] => 9개나옴

4. combinations_with_replacement

combinations 에서 중복 허용

rom itertools import combinations_with_replacement


data = ['A', 'B', 'C']


result = list(combinations_with_replacement(data, 2)) # 데이터중 2개를 뽑아 순서없이 나열(중복 조합)


print(result) => [('A', 'A'),('A', 'B'), ,,,,,,,, , ('C', 'C')] =>6개 나옴

 

 

 


📌 3. heapq - Heap 기능 (기본 : 최소 힙)

PriorityQueue 보다 빠름.

원소 삽입: heapq.heappush()

원소 꺼냄: heapq.heappop()

 

기본 최소 힙 코드)

import heapq

def heapsort(iterable):
    h=[]
    result =[]
    
    #모든 원소 차례로 힙에 삽입
    for value in iterable:
        heapq.heappush(h,value); # h 에 value 를 push
    
    # 힙의 모든 원소 꺼내기
    for i in range(len(h)):
        result.append(heapq.heappop(h))
    return result
result = heapsort([2,1,3,0,5,4])
print(result) # [0,1,2,3,4,5] 최소힙 - 오름차순 정렬

 

최대 힙 구현 코드)

값에 - 를 붙여서 넣는다!

import heapq

def heapsort(iterable):
    h=[]
    result =[]
    
    #모든 원소 차례로 힙에 삽입
    for value in iterable:
        heapq.heappush(h,-value); # 원소에 - 를 붙여 넣으면 반대로 됨!
    
    # 힙의 모든 원소 꺼내기
    for i in range(len(h)):
        result.append(-heapq.heappop(h)) # 다시 원소에 - 붙이기
    return result
result = heapsort([2,1,3,0,5,4])
print(result) # [5,4,3,2,1,0] 최소힙 - 오름차순 정렬

 

 

 


📌4. bisect - 이진 탐색 쉽게 구현

'정리된 배열'에서 특정한 원소 찾을때 매우 효과적!

bisect_left(), bisect_right() 함수가 가장 중요, 둘다 시간복잡도 O(logN)

- bisect_left(a,x) : 정렬 순서 유지, 리스트 a에 데이터 x를 삽입 할 가장 왼쪽 인덱스 찾음

- bisect_right(a,x): 정렬 순서 유지, 리스트 a에 데이터 x를 삽입 할 가장 오른쪽 인덱스 찾음

from bisect import bisect_left, bisect_right
a=[1,2,4,4,8]
x=4
print(bisect_left(a,x) => 2
print(bisect_right(a,x) =>4

bisect_left(), bisect_right() : ' 정렬된 리스트'에서 '값이 특정 범위에 속하는 원소의 개수' 구할때 효과적!!

from bisect import bisect_left, bisect_right

def count(a, left_value, right_value):

    left_index = bisect_left(a, left_value)
    right_index = bisect_right(a, right_value)
    return right_index - left_index
    
a=[1,2,3,3,3,3,4,5]

# a 리스트에서 값이 3인 데이터의 갯수 
print(count(a,3,3)) # 답:4

# a 리스트에서 [-1,3] 범위에 있는 데이터의 갯수
print(count(a,-1,3)) # 답:6
    

 

 


📌5. collections - 유용한 자료구조  ex) deque, Counter

1. deque

보통 큐 구현 할 때 사용!! (스택도 가능, Queue 라이브러리보다 빠름)

- list 는 삭제, 삽입이 모두 '가장 뒤쪽 원소' 기준임!

- but, deque 이용시 popleft()로 첫번째 원소 삭제, append(x)로 마지막 인덱스에 삽입

 (pop()으로 마지막 원소 삭제, appendleft(x)로 첫번째 인덱스에 삽입 가능)

from collections import deque

data = deque([2,3,4])
data.appendleft(1)
data.append(5)

print(data) # deque([1,2,3,4,5])
print(list(data)) # [1,2,3,4,5] 리스트 자료형으로 변환

2. Counter: 등장 횟수 셈! 

 리스트 같은 iterable 객체에서, 내부 원소가 몇번씩 등장했는지 알려줌.

from collections import Counter

counter = Counter(['r','b','r','b','g','b'])

print(counter['b']) # 'b' 등장횟수, 답: 3
print(counter['o'] # 1
print(dict(counter)) # {'r':2, 'b':3, 'g':1}

 

 


📌6. math

1. factorial(x) => x의 팩토리얼 값 출력

2. sqrt(x) => x의 제곱근 출력

3. gcd(a,b) => a 와 b의 최대공약수 출력

4. 상수 pi , e => 파이와 자연상수 출력

import math

print(math.factorial(5))   # 120
print(math.sqrt(7))        # 2.6457513110645907
print(math.gcd(21,14))   # 7
print(math.pi)              # 3.14159....93
print(math.e)               # 2.71828......45
728x90

댓글