def sort_stack(s): def insert_sorted(item): while not s_aux.is_empty() and s_aux.peek() > item: s.push(s_aux.pop()) s_aux.push(item) s_aux = Stack() while not s.is_empty(): insert_sorted(s.pop()) while not s_aux.is_empty(): s.push(s_aux.pop()) return s
class StackMin(Stack): def __init__(self): self._mins = Stack() Stack.__init__(self) # O(1) def min(self): if self._mins.is_empty(): raise EmptyStackError return self._mins.peek() # O(1) def pop(self): popped = Stack.pop(self) if popped == self.min(): self._mins.pop() return popped # O(1) def push(self, item): if self.is_empty() or item <= self.min(): self._mins.push(item) Stack.push(self, item)
def __init__(self): self.SIn = Stack() self.SOut = Stack()
class MyQueue(): def __init__(self): self.SIn = Stack() self.SOut = Stack() # O(1) def add(self, item): self.SIn.push(item) return self # O(n) def _move(self): while not self.SIn.is_empty(): self.SOut.push(self.SIn.pop()) return self # O(1) amortized def peek(self): if self.is_empty(): raise EmptyMyQueueError if self.SOut.is_empty(): self._move() return self.SOut.peek() # O(1) amortized def remove(self): if self.is_empty(): raise EmptyMyQueueError if self.SOut.is_empty(): self._move() return self.SOut.pop() # O(1) def is_empty(self): return self.SIn.is_empty() and self.SOut.is_empty() def __repr__(self): return f'{repr(self.SIn)} | {repr(self.SOut)[::-1]}'
def push(self, item): if self.is_empty() or self._stacks[-1].length() == self._size: self._stacks.append(Stack()) self._stacks[-1].push(item) return self
def push(self, item): if self.is_empty() or item <= self.min(): self._mins.push(item) Stack.push(self, item)
def pop(self): popped = Stack.pop(self) if popped == self.min(): self._mins.pop() return popped
def __init__(self): self._mins = Stack() Stack.__init__(self)