Study Record

[파이썬] 알고리즘 라이브러리 본문

서버보안/리눅스 서버보안

[파이썬] 알고리즘 라이브러리

초코초코초코 2022. 3. 2. 15:10
728x90

Queue

from collections import deque

# 큐 - 양방향으로 데이터를 추가하고 삭제할 수 있다.
queue = deque()

# 선입
queue.append(3)
queue.append(5)
queue.append(1)

# 선출
print(queue.popleft())
print(queue.popleft())
print(queue.popleft())

 

우선순위 Queue

from queue import PriorityQueue

# 우선순위 큐
priority = PriorityQueue()

# 값 선입
priority.put(8)
priority.put(3)
priority.put(1)

# 값 선출
print(priority.get(), end=" ")
print(priority.get(), end=" ")
print(priority.get(), end=" ")

# 비어있는지 확인
print(priority.empty())

priority = PriorityQueue()

priority.put((5, 5))
priority.put((2, 7))
priority.put((4, 1))

print(priority.get())

 

정렬

a = [1, 4, 2, 6, 8, 9]
b = [2, 3, 6, 1, 8, 3]

# 오름차순 정렬
a.sort()
print(a)

# 내림차순 정렬
b.sort(reverse=True)
print(b)

# 새로운 배열에 할당
print(sorted(a))
print(sorted(b, reverse=True))

# 여러가지 원소가 있을경우 정렬 기준 정하기
array = [['a', 1], ['c', 4], ['b', 3], ['d', 2]]
array.sort(key=lambda x: x[0])  # array.sort() 와 동일
print(array)

array.sort(key=lambda x: x[1])  # 두번째 요소에 대한 정렬
print(array)

 

깊은 복사

# 깊은 복사
import copy

a = [1,3,5,7,9]
b = copy.deepcopy(a)
c = [_ for _ in a]

 

728x90