Beispiel #1
0
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
Beispiel #2
0
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)
Beispiel #3
0
 def __init__(self):
     self.SIn = Stack()
     self.SOut = Stack()
Beispiel #4
0
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]}'
Beispiel #5
0
 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
Beispiel #6
0
 def push(self, item):
     if self.is_empty() or item <= self.min():
         self._mins.push(item)
     Stack.push(self, item)
Beispiel #7
0
 def pop(self):
     popped = Stack.pop(self)
     if popped == self.min():
         self._mins.pop()
     return popped
Beispiel #8
0
 def __init__(self):
     self._mins = Stack()
     Stack.__init__(self)