240702 TIL #440 파이썬 코테용 라이브러리

김춘복·2024년 7월 1일
0

TIL : Today I Learned

목록 보기
440/494

Today I Learned

파이썬 코테에 자주 쓰이는 라이브러리를 정리해보았다.


파이썬 라이브러리

파이썬 내장함수

sum : iterable의 합계
max : 최대값
min : 최소값
sorted : 정렬. reverse=True면 내림차순. key=lambda x: ~~~를 쓰면 람다로 정렬 가능
len : 요소의 수
eval : 식을 계산해줌

# sum 함수
list1 = [10,2,8,4,6]
sum_result = sum(list1)
print(sum_result) # 30

# min, max
print(min(list1)) # 2
print(max(list1)) # 10

# sorted
sorted_list = sorted(list1)
print(sorted_list) # [2, 4, 6, 8, 10]
sorted_list = sorted(list1, key=lambda x:-x)
print(sorted_list) # [10, 8, 6, 4, 2]

# 기타
print(len(list1)) # 5
print("Answer is {}.".format(eval('7+3*6-4^2'))) # Answer is 23.

itertools

순열 : from itertools import permutations
조합 : from itertools import combinations
list(permutations(리스트명, 개수) 형식으로 사용

# 순열
from itertools import permutations
data = ['Q', 'W', 'E']
print(list(permutations(data, 3)))
# [('Q', 'W', 'E'), ('Q', 'E', 'W'), ('W', 'Q', 'E'), ('W', 'E', 'Q'), ('E', 'Q', 'W'), ('E', 'W', 'Q')]

# 조합
from itertools import combinations
print(list(combinations(data, 2))) # [('Q', 'W'), ('Q', 'E'), ('W', 'E')]

heapq

import heapq
힙을 사용하기 쉽고 빠르게 만들어준 라이브러리
우선순위큐보다 빠르다
최대힙으로 사용하려면 요소를 넣을때 -1을 곱해서 넣고 뺄 때 다시 -1을 곱해준다.

# 기본적으로 최소힙(오름차순 정렬)
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 5)
heapq.heappush(heap, 2)
print(heap) # [1, 2, 5, 3]

smallest = heapq.heappop(heap)
print(smallest) # 1
print(heap) # [2, 3, 5]

bisect

from bisect import bisect_left, bisect_right
import bisect
이진탐색용 라이브러리
정렬된 리스트에 요소를 어느 위치에 넣을 수 있는지 이진탐색으로 찾아주고 삽입도 가능하다.

from bisect import bisect_left, bisect_right
list2 = [1,5,7,13,25,25,33,45]
print(bisect_left(list2, 25)) # 4
print(bisect_right(list2, 25)) # 6
import bisect
bisect.insort_left(list2, 22) # 삽입
print(list2) # [1, 5, 7, 13, 22, 25, 25, 33, 45]

collections

자주 쓰는 자료구조
deque : from collections import deque
append와 pop은 오른쪽(뒤에서), appendleft와 popleft는 왼쪽(앞에서)
deque를 이용해서 스택과 큐를 사용할 수 있다.
Counter : from collections import Counter
iterable에 있는 요소의 수를 세어서 dict와 비슷한 형태로 만들어준다.

from collections import Counter
list4 = ['a', 'b', 'a', 'a', 'a', 'c', 'b', 'e', 'e', 'd', 'a']
c = Counter(list4)
print(c["a"]) # 5
print(dict(c)) # {'a': 5, 'b': 2, 'c': 1, 'e': 2, 'd': 1}

math

import math
수학과 관련된 계산을 해준다.

import math
print(math.factorial(6)) # 720
print(math.sqrt(36)) # 6.0
print(math.gcd(49, 35)) # 7
profile
꾸준히 성장하기 위해 매일 log를 남깁니다!

0개의 댓글