about summary refs log tree commit diff
path: root/universe/data_structures_and_algorithms/queue-two-stacks.py
blob: 63da08ebf79a11634f1cace1cd94551c1cf6e477 (plain) (blame)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import unittest


################################################################################
# Solution
################################################################################
class QueueTwoStacks(object):
    def __init__(self):
        self.a = []
        self.b = []

    def enqueue(self, x):
        self.a.append(x)

    def dequeue(self):
        if self.b:
            return self.b.pop()
        else:
            while self.a:
                self.b.append(self.a.pop())
            return self.dequeue()


################################################################################
# Tests
################################################################################
class Test(unittest.TestCase):
    def test_basic_queue_operations(self):
        queue = QueueTwoStacks()
        queue.enqueue(1)
        queue.enqueue(2)
        queue.enqueue(3)
        actual = queue.dequeue()
        expected = 1
        self.assertEqual(actual, expected)
        actual = queue.dequeue()
        expected = 2
        self.assertEqual(actual, expected)
        queue.enqueue(4)
        actual = queue.dequeue()
        expected = 3
        self.assertEqual(actual, expected)
        actual = queue.dequeue()
        expected = 4
        self.assertEqual(actual, expected)

    def test_error_when_dequeue_from_new_queue(self):
        queue = QueueTwoStacks()
        with self.assertRaises(Exception):
            queue.dequeue()

    def test_error_when_dequeue_from_empty_queue(self):
        queue = QueueTwoStacks()
        queue.enqueue(1)
        queue.enqueue(2)
        actual = queue.dequeue()
        expected = 1
        self.assertEqual(actual, expected)
        actual = queue.dequeue()
        expected = 2
        self.assertEqual(actual, expected)
        with self.assertRaises(Exception):
            queue.dequeue()


unittest.main(verbosity=2)