asb: head /dev/brain > /dev/www

My home, musings, and wanderings on the world wide web.

HackerRank: Implementing a queue using two stacks.

The idea is to keep an inbox and outbox using stacks. Here is a simple implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Queue(object):

    def __init__(self):
        self._inbox = Stack()
        self._outbox = Stack()

    def _refill(self):
        if not self._outbox:
            while self._inbox:
                self._outbox.push(self._inbox.pop())

    def peek(self):
        self._refill()
        try:
            return self._outbox.peek()
        except IndexError:
            raise EmptyQueueError()

    def pop(self):
        self._refill()
        try:
            retval = self._outbox.pop()
        except IndexError:
            raise EmptyQueueError()
        else:
            return retval

    def push(self, value):
        self._inbox.push(value)


class Stack():

    def __init__(self, iterable=None):
        self._data = [] if iterable is None else list(iterable)

    def __bool__(self):
        return bool(self._data)

    def peek(self):
        return self._data[-1]

    def pop(self):
        return self._data.pop()

    def push(self, value):
        self._data.append(value)


class EmptyQueueError(BaseException):
    pass