A stack is a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle.
→ 스택은 LIFO 정책을 갖고 있는 객체들의 집합이다.
→ 유저는 스택의 객체들을 아무때나 삽입이 가능하지만 삽입된 객체에 접근하거나 제거하기 위해서는 앞서 말한 정책을 따라야한다. 소위 말해 “top”에서만 접근이 가능한 것이다.
→ 인터넷 웹 브라우저에서 페이지 창의 뒤로가기 등의 기능은 스택의 정책을 사용한다고 볼 수 있다. 뒤로가기 버튼을 누르면 바로 이전 페이지가 pop되는것이다.
스택의 추상화 데이터 타입인 예를들어 S (instance)는다음과 같은 methods들을 지원한다.
S.push(e) : element e를 stack S의 top에 더한다.
S.pop() : top element를 반환하고 이를제거한다. (is empty 시 error)
S.top() : S의 top의 a reference element 를 반환한다. (is empty 시 error)
S.is_empty() : S가 아무런 element를 가지고 있지 않다면 True 를 반환한다.
len(S) : ...
Simple Array-Based Stack Implementation
Implementing a Stack Using a Python List
class ArrayStack:
def __init__(self):
self._data = [] # empty python list for internal storage.
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
if self.is_empty():
raise Empty("Empty stack!")
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty("Empty stack!")
return self._data.pop()
→ Array-based stack에서는 각 메서드가 상수 시간의 시간복잡도를 가진다. 다만 push 그리고 pop의 기능은 amortized analysis상 list class랑 비슷한 bounds를 가지게 되고, push를 어디서 어떻게 하느냐에 따라 까지도 최악의 경우 가질 수 있다. 이는 pop도 마찬가지이다.
1.3 Reversing Data Using a Stack
1.4 Matching Parentheses and HTML Tags
• Parentheses: “(” and “)”
• Braces: “{” and “}”
• Brackets: “[” and “]”
def is_matched(expr): # 모두 매칭에 성공하면 True를 반환한다. 그렇지 않은 경우 False.
left_group = "({["
right_group = ")}]"
S = ArrayStack()
for c in expr:
if c in left_group:
S.push(c)
elif c in right_group:
if S.is_empty():
return False
item = S.pop() # item을 꺼내기 이전 S이 비어있는지 항상 확인부터 한다.
if right_group.index(c) != left_group.index(item) : return False
return S.is_empty()
# stack이 비어있다면 모든 left_group이 꺼내져서 right_group과 검사한 셈이 되므로
# Maching delimiters에 성공한다.
The queue abstract data type defines a collection that keeps objects in a
sequence, where element access and deletion are restricted to the first element in the queue, and element insertion is restricted to the back of the sequence.
→ 이에 대한 정의를 자세히 읽어보면 Queue라는 자료 구조는 역시 시퀀스 객체들에 대한 집합체에 대해 정의한 것이며, 각 원소들은 첫번째(first) 또는 마지막 (back)에서 접근이나 삭제가 허용되는 것을 알 수 있다. 이렇게 앞, 뒤로 자료의 삽입 삭제가 가능하며 먼저 들어온 원소가 먼저 나가는 정책을 가져 First-in, first-out FIFO 라고 불린다.
2.2 Array-Based Queue Implementation
Using an Array Circularly
Adding and Removing Elements
이런 형태는, 제한된 사이즈 10을 넘어갈 때 특징을 더욱 잘 살펴볼 수 있다.
예를 들어 front가 8이고 3개의 element가 존재 할 때, 삽입될 위치는 (8+3) % 10 11% 10 → 1.
Python Queue Implementation
from queue import Empty
class ArrayQueue:
DEFAULT_CAPACITY = 10
def __init__(self):
self._data = [None] * ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
return len(self._size)
def __str__(self):
return str(self._data)
def is_empty(self):
return self._size == 0
def first(self):
if self.is_empty():
raise Empty("Queue is empty.")
return self._data[self._front]
def enqueue(self,e):
if self._size == len(self._data):
self._resize(2*len(self._data)) # insert index
avail = (self._front + self._size) % len(self._data)
self._data[avail] = e
self._size +=1
return
def dequeue(self):
if self.is_empty():
raise Empty("Queue is empty.") # Empty class
item = self._data[self._front]
self._data[self._front] = None
self._front = (self._front + 1) % len(self._data)
self._size -=1
if 0 < self_size < len(self._data) //4 :
self._resize(len(self._data) //2)
return item
def _resize(self, cap):
old = self._data
self._data = [None] * cap
walk = self._front
for k in range(self._size):
self._data[k] = old[walk]
walk = (1+ walk) % len(old)
self._front = 0
queue - A synchronized queue class - Python 3.10.5 documentation
“Queue-like data structure that supports insertion and deletion at both the front and the back of the queue.”
→ 큐 자료구조는 First In First Out 이라는 정책에 맞게, 데이터가 나가는 방향이 앞으로 정해져있다. Double-ended Queue의 경우 이와 다르게 데이터의 삽입과 삭제를 앞, 뒤 모두 지원하며 이러한 구조의 특성 때문에 앞선 이름이 붙었다. 다른 말로 deque 데크라고도 부른다.
deque의 필요성과 관련해서 서적에는 레스토랑에서 손님을 관리하는 것에 그 비유를 들고 있는데, 첫 번 째 사람이 이용 가능한 테이블이 없어서 제거되었다가 다시 앞에 추가될 수 있고 마지막 손님이 기다리지 못하고 그냥 나가게 될 수도 있다. 이렇게 좀 더 general한 data structure에 대해서 이야기를 하고 있다.
3-1 The Deque Abstract Data Type
Resizing the Queue
Shrinking the Underlying Array
DataStructureandAlgorithm/lecture6.py at master · kosohae/DataStructureandAlgorithm