Today
Total
07-03 00:02
관리 메뉴

T-coding

코딩테스트를 위한 파이썬 문법(주요 라이브러리 문법) 본문

Python

코딩테스트를 위한 파이썬 문법(주요 라이브러리 문법)

Tcoding 2023. 3. 2. 11:11
728x90
728x90

나동빈 님의 이것이 취업을 위한 코딩 테스트다 with 파이썬 책을 보고 참고하여 작성한 글입니다.

이것이 취업을 위한 코딩 테스트다 with 파이썬 - 나동빈

 

내장 함수

# sum() 함수
result = sum(1, 2, 3, 4, 5])
print(result) # 15


# min() 함수
result = min(7, 3, 5, 2)
print(result) # 2


# max() 함수
result = max(7, 3, 5, 2)
print(result) # 7


# sorted() 함수
result = sorted([9, 1, 8, 5, 4]) # 오름차순 정렬
print(result) # 1 4 5 8 9

result = sorted([9, 1, 8, 5, 4], reverse = True) # 내림차순 정렬
print(result) # 9 8 5 4 1

result = sorted([('홍길동', 35), ('이순신', 75), ('아무개', 50)], key = lambda x: x[1], reverse = True)
print(result) # [('이순신', 75), ('아무개', 50), ('홍길동', 35)]

 

 

itertools

반복되는 데이터 처리 기능 포함 라이브러리

permutations : iterable 객체에서 r개의 데이터를 뽑아 일렬로 나열하는 모든 경우(순열)을 계산

# permutations example
from itertools import permutations

data = ['A', 'B', 'C']
result = list(permutations(data, 3)) # 모든 순열 구하기
print(result) # [('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]

 

combinations : iterable 객체에서 r개의 데이터를 뽑아 순서를 고려하지 않고 나열하는 모든 경우(조합)를 계산

# combinations example
from itertools import combinations

data = ['A', 'B', 'C']
result = list(combinations(data, 2)) # 2개를 뽑는 모든 조합 구하기
print(result) # [('A', 'B'), ('A', 'C'), ('B', 'C')]

 

product :  permutations와 같이 iterable 객체에서 r개의 데이터를 뽑아 일렬로 나열하는 모든 경우(순열)을 계산한다. 다만 원소를 중복하여 뽑는다.

# product example
from itertools import product

data = ['A', 'B', 'C']
result = list(proudct(data, repeat = 2)) # 2개를 뽑는 모든 순열 구하기(중복 허용)
print(result) # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]

 

combinations_with_replacement : combinations와 같이 iterable 객체에서 r개의 데이터를 뽑아 순서를 고려하지 않고 나열하는 모든 경우(조합)를 계산한다. 다만 원소를 중복해서 뽑는다.

# combinations_with_replacement example
from itertools import combinations_with_replacement

data = ['A', 'B', 'C']
result = list(combinations_with_replacement(data, 2)) # 2개를 뽑는 모든 조합 구하기(중복 허용)
print(result) # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

 

 

heapq

다양한 알고리즘에서 우선순위 큐 기능을 구현하고자 할 때 사용

#최소 힙
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([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print(result) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


#최대 힙
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([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
print(result) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

 

 

bisect

정렬된 배열에서 특정한 원소를 찾아야 할 때 사용

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

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

출처 : 코딩테스트를 위한 파이썬 문법 with 파이썬 - 나동빈

# 기본 사용법
from bisect import bisect_left, bisect_right

a = [1, 2, 4, 4, 8]
x = 4

print(bisect_left(a, x)) # 2
print(bisect_left(a, x)) # 4


# 정렬된 리스트에서 값이 특정 범위에 속하는 원소의 개수 구하기
from bisect import bisect_left, bisect_right

# 값이 [left_value, right_value]인 데이터의 개수를 반환하는 함수
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
 
a = [1, 2, 3, 3, 3, 3, 4, 4, 8, 9]

# 값이 4인 데이터 개수 출력
print(count_by_range(a, 4, 4)) # 2

# 값이 [-1, 3] 범위에 있는 데이터 개수 출력
print(count_by_range(a, -1, 3)) # 6

 

 

collections

파이썬에서는 deque를 사용해 큐를 구현

# deque example
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]

 

Counter : 등장 횟수를 세는 기능을 제공

# Counter example
from collections import Counter

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

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

 

 

math

# factorial example
import math

print(math.factorial(5)) # 120


# sqrt(제곱근) example
import math

print(math.sqrt(7)) # 2.6457513110645907


# gcd(최대 공약수) example
import math

print(math.gcd(21, 14)) # 7


# pi(파이), e(자연상수) example
import math

print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
728x90
300x250