class Tower:
    def __init__(self, index):
        self.disks = Stack()
        self.index = index

    def index(self):
        return self.index

    def add(self, disk):
        if len(self.disks) != 0 and self.disks.peek() <= disk:
            raise Exception("Error placing disk " + str(disk))
        else:
            self.disks.push(disk)

    def move_top_to(self, tower):
        top = self.disks.pop()
        tower.add(top)
        print("Move disk " + str(top) + " from " + str(self.index()) + " to " +
              str(tower.index()))

    def move_disks(self, n, destination, buffer):
        if n > 0:
            self.move_disks(n - 1, buffer, destination)
            self.move_top_to(destination)
            buffer.move_disks(n - 1, destination, self)
 def push(self, item):
     last_stack = self.get_last_stack()
     if last_stack is not None and len(last_stack) is not self.capacity:
         last_stack.push(item)
     else:
         stack = Stack()
         stack.push(item)
         self.stacks.append(stack)
示例#3
0
class MyQueue:
    def __init__(self):
        self.s1 = Stack()
        self.s2 = Stack()

    def enqueue(self, item):
        self.s1.push(item)

    def dequeue(self):
        if not self.s2.is_empty():
            return self.s2.pop()

        while not self.s1.is_empty():
            self.s2.push(self.s1.pop())

        return self.s2.pop()
def sort(stack):
    r = Stack()

    while not stack.is_empty():
        tmp = stack.pop()
        while not r.is_empty() and r.peek() > tmp:
            stack.push(r.pop())
        r.push(tmp)

    return r
class MinStack(Stack):
    def __init__(self):
        super().__init__()

        self.s2 = Stack()

    def push(self, item):
        if item < self.min():
            self.s2.push(item)

        super().push(item)

    def pop(self):
        item = super().pop()

        if item is self.min():
            self.s2.pop()

        return item

    def min(self):
        if self.s2.is_empty():
            return float('inf')
        else:
            return self.s2.peek()
    def __init__(self):
        super().__init__()

        self.s2 = Stack()
示例#7
0
 def __init__(self):
     self.s1 = Stack()
     self.s2 = Stack()
 def __init__(self, index):
     self.disks = Stack()
     self.index = index