내장함수

Coding Test
Author

SEOYEON CHOI

Published

January 15, 2023

주요 라이브러리 문법

내장 함수

sum

sum([1,2])
3

min

min([14,5,6,0,3])
0

max

max(1,3,6,3,33)
33

eval

수학 수식이 문자열 형식으로 들어오면 해당 수식을 계산한 결과를 반환

eval("3+4")
7
eval("3*4")
12

sorted

sorted([1,2,3,2,3])
[1, 2, 2, 3, 3]
sorted([1,2,3,2,3],reverse=True)
[3, 3, 2, 2, 1]

\(\star\) List 형식이어야 함

sorted(1,2,3,2,3)
TypeError: sorted expected 1 argument, got 5

group 가능

sorted([('a',3),('b',4)],reverse=True)
[('b', 4), ('a', 3)]

사실 list 는 iterable 객체라 기본으로 sort()함수 가지고 있음

a = [4,1,3,4]
a.sort()
print(a)
[1, 3, 4, 4]

itertools

permutations 순열(중복 허용하지 않음)

from itertools import permutations

data = [1,3,5]

result = list(permutations(data,3))

print(result)
[(1, 3, 5), (1, 5, 3), (3, 1, 5), (3, 5, 1), (5, 1, 3), (5, 3, 1)]

combinations 조합(중복 허용하지 않음)

from itertools import combinations

data = ['a','r','t','e']
result = list(combinations(data,2))

print(result)
[('a', 'r'), ('a', 't'), ('a', 'e'), ('r', 't'), ('r', 'e'), ('t', 'e')]

product 순열(중복 허용)

from itertools import product

data = [1,3,5]

result = list(product(data,repeat=3))

print(result)
[(1, 1, 1), (1, 1, 3), (1, 1, 5), (1, 3, 1), (1, 3, 3), (1, 3, 5), (1, 5, 1), (1, 5, 3), (1, 5, 5), (3, 1, 1), (3, 1, 3), (3, 1, 5), (3, 3, 1), (3, 3, 3), (3, 3, 5), (3, 5, 1), (3, 5, 3), (3, 5, 5), (5, 1, 1), (5, 1, 3), (5, 1, 5), (5, 3, 1), (5, 3, 3), (5, 3, 5), (5, 5, 1), (5, 5, 3), (5, 5, 5)]

combinations_with_replacement(중복 허용)

from itertools import combinations_with_replacement

data = ['a','r','t','e']
result = list(combinations_with_replacement(data,2))

print(result)
[('a', 'a'), ('a', 'r'), ('a', 't'), ('a', 'e'), ('r', 'r'), ('r', 't'), ('r', 'e'), ('t', 't'), ('t', 'e'), ('e', 'e')]

heapq

다익스트라 최단 경로 알고리즘을 포함해 다양한 알고리즘에서 우선순위 큐 기능을 구현하고자 할 때 사용

import heapq

def heapsort(iterable):
    h = []
    result = []
    for value in iterable:
        heapq.heappush(h,value)
    for _ in range(len(h)):
        result.append(heapq.heappop(h))
    return result
    
result = heapsort([1,4,5,6,2,2,77,3,25])
print(result)
[1, 2, 2, 3, 4, 5, 6, 25, 77]
a = []
heapq.heappush(a,5)
a
[5]
heapq.heappush(a,3)
a
[3, 5]
heapq.heappush(a,2)
a
[2, 5, 3]
heapq.heappop(a)
2

max heap

import heapq

def heapsort(iterable):
    h = []
    result = []
    for value in iterable:
        heapq.heappush(h,-value)
    for _ in range(len(h)):
        result.append(-heapq.heappop(h))
    return result
    
result = heapsort([1,4,5,6,2,2,77,3,25])
print(result)
[77, 25, 6, 5, 4, 3, 2, 2, 1]
a = []
heapq.heappush(a,-5)
a
[-5]
heapq.heappush(a,-3)
a
[-5, -3]
heapq.heappush(a,-2)
a
[-5, -3, -2]
-heapq.heappop(a)
5

bisect

이진 탐색 구현

  • 정렬된 상태여야 함

bisect_left(a,x)

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

bisect_right(a,x)

정렬된 순서를 유지하면서 리스트 a에 데이터 x를 삽입할 가장 오른쪽 인덱스를 찾는 메서드

from bisect import bisect_left, bisect_right

a = [1,2,5,6,33,3]
x = 3
b = sorted(a)
print(b)
print(bisect_left(b,x))
print(bisect_right(b,x))
[1, 2, 3, 5, 6, 33]
2
3
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

a = [1,4,5,7,5,3,6,7,9,99,2,22]
b = sorted(a)

print(count_by_range(b,5,5))

print(count_by_range(b,-1,3))
2
3

collections

deque

from collections import deque

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

print(data)

print(list(data))
deque([3, 2, 5, 4, 6, 3, 1])
[3, 2, 5, 4, 6, 3, 1]
data.pop()
1
data
deque([3, 2, 5, 4, 6, 3])
data.popleft()
3
data
deque([2, 5, 4, 6, 3])

Counter

등장 횟수 세는 기능

from collections import Counter

counter = Counter(['d','d','d','a','e','q','d'])

print(counter['d'])
print(counter['a'])
print(dict(counter),"\n사전자료형으로 반환")
4
1
{'d': 4, 'a': 1, 'e': 1, 'q': 1} 
사전자료형으로 반환
counter
Counter({'d': 4, 'a': 1, 'e': 1, 'q': 1})

math

import math
print(math.factorial(4))
24
4*3*2*1
24
import math
print(math.sqrt(25))
5.0

최대 공약수

import math
print(math.gcd(30,25))
5
import math
print(math.pi)
print(math.e)
3.141592653589793
2.718281828459045