PS에서 자주 사용되는 python 라이브러리

김유진·2022년 3월 6일
0

Algorithm

목록 보기
1/9

오늘은 알고리즘 풀이 시 자주 사용되는 python 라이브러리에 대해서 알아보고자 한다.

1. 알고리즘 수행 시간 측정

import time
start_time = time.time() # 측정 시작

#프로그램 소스코드
end_time = time.time()
print("time : ", end_time - start_time) # 수행 시간 출력 

2. python 내장 함수

① 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)
  • sorted() with key
    이 때에는 정렬 기준을 명시해 줄 수 있다. 정렬 기준은 lambda 함수 형태로 간단히 넣어주는 경우가 많다. 아래 제시된 것은 tuple의 두번째 원소를 기준으로 정렬함을 안내하는 것이다.
array = [('홍길동', 35), ('이순신',75),('아무개',50)]
result=sorted(array, key=lambda x : x[1], reverse = True)
print(result)

결론은 [('이순신', 75), ('아무개',50),('홍길동', 35)] 로 출력된다. (오름차순으로)

3. 순열 구하는 라이브러리

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')]

4. 조합 구하는 라이브러리

from itertools import combinations

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

result = list(combinations(data,2)) #2개를 뽑는 모든 조합 구하기
print(result)

실행 결과 : [('A',B'),('A','C'),('B','C')]

5. 중복이 허용되는 순열과 조합

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)

6. Counter

등장 횟수를 세는 기능 제공
리스트와 같은 반복 가능한 객체가 주어졌을 때 내부의 원소가 몇 번씩 등장했는지를 알려줍니다.

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 }

7. 최대 공약수와 최소 공배수

최대 공약수를 구해야 할 때는 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)) #최소 공배수 계산

8. python에서 말하는 시간

대략 2십만회 (200,000) 까지는 1초라고 생각해도 무관

0개의 댓글