오늘은 알고리즘 풀이 시 자주 사용되는 python 라이브러리에 대해서 알아보고자 한다.
import time
start_time = time.time() # 측정 시작
#프로그램 소스코드
end_time = time.time()
print("time : ", end_time - start_time) # 수행 시간 출력
① sum 함수
다수의 데이터를 포함하는 리스트나 튜플 등이 들어왔을 때 그 원소들의 합을 반환한다.
result = sum ([1,2,3,4,5])
print(result)
② min, max 함수
가장 작은 값과 가장 큰 값을 얻으려고 할 때. 인자로 여러 개를 넣을 수 있다.
min_result = min(7,3,5,2)
max_result = max(7,3,5,2)
print(min_result, max_result)
③ eval 함수
수식으로 표현된 식이 있을 때 해당 식의 결과를 수의 형태로 반환해 주는 것이다.
result = eval("(3+5)*7")
print(result)
④ sorted 함수
반복 가능한 객체의 원소를 정렬. 오름차순이 기본값인데,
reverse=True 를 제시하면 내림차순으로 변경 가능하다.
result = sorted([9,1,8,5,4])
reverse_result = sorted([9,1,8,5,4],reverse=True)
print(result)
print(reverse_result)
array = [('홍길동', 35), ('이순신',75),('아무개',50)]
result=sorted(array, key=lambda x : x[1], reverse = True)
print(result)
결론은 [('이순신', 75), ('아무개',50),('홍길동', 35)] 로 출력된다. (오름차순으로)
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')]
from itertools import combinations
data=['A','B','C']
result = list(combinations(data,2)) #2개를 뽑는 모든 조합 구하기
print(result)
실행 결과 : [('A',B'),('A','C'),('B','C')]
2개를 뽑는 모든 순열을 구해보자. (중복 허용)
from itertools import product
data = ['A','B','C']
result = list(product(data,repeat=2))
print(result)
from itertools import combinations_with_replacement
2개를 뽑는 모든 조합을 구해보자. (중복 허용)
data = ['A','B','C']
result = list(combinations_with_replacement(data,2))
print(result)
등장 횟수를 세는 기능 제공
리스트와 같은 반복 가능한 객체가 주어졌을 때 내부의 원소가 몇 번씩 등장했는지를 알려줍니다.
from collections import Counter
counter = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(counter['blue']) #blue가 등장한 횟수 출력
print(counter['green']) # green이 등장한 횟수 출력
print(dict(counter)) # 사전 자료형으로 반환해라
사전 자료형 반환 출력결과 : {'red' :2 ,'blue' :3, 'green' :1 }
최대 공약수를 구해야 할 때는 math 라이브러리의 gcd() 함수 이용
import math
#최소 공배수를 구하는 함수
def lcm(a,b):
return a*b //math.gcd(a,b)
a = 21
b = 14
print(math.gcd(21,14)) #최대 공약수 계산
print(lcm(21, 14)) #최소 공배수 계산
대략 2십만회 (200,000) 까지는 1초라고 생각해도 무관