Mercurial > public > think_complexity
comparison ch4ex1.py @ 22:84e183b40c63
Added exercises 1 and 2 from chapter 4.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Mon, 31 Dec 2012 18:58:21 -0600 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
21:55880b29b4d4 | 22:84e183b40c63 |
---|---|
1 """Section 4.2, exercise 1 of Allen Downey's Think Complexity book. | |
2 | |
3 "Write an implementation of a FIFO using either a doubly-linked list or | |
4 a circular buffer." | |
5 | |
6 """ | |
7 | |
8 class Node(object): | |
9 | |
10 def __init__(self, data): | |
11 self.prev = self.next = None | |
12 self.data = data | |
13 | |
14 class Fifo(object): | |
15 | |
16 def __init__(self): | |
17 self.first = None | |
18 self.last = None | |
19 | |
20 def append(self, val): | |
21 """Append a value onto the back of the queue.""" | |
22 | |
23 node = Node(val) | |
24 | |
25 if self.last: | |
26 self.last.next = node | |
27 node.prev = self.last | |
28 | |
29 self.last = node | |
30 | |
31 if not self.first: | |
32 self.first = node | |
33 | |
34 def pop(self): | |
35 """Remove and return the value at the front of the queue. | |
36 | |
37 Raises an IndexError if the queue is empty. | |
38 """ | |
39 if not self.first: | |
40 raise IndexError | |
41 | |
42 node = self.first | |
43 self.first = node.next | |
44 node.prev = node.next = None | |
45 | |
46 if self.last is node: | |
47 self.last = None | |
48 | |
49 return node.data | |
50 | |
51 def empty(self): | |
52 """Returns True if the queue is empty and False otherwise.""" | |
53 return self.first is None and self.last is None | |
54 | |
55 | |
56 if __name__ == '__main__': | |
57 import random | |
58 values = range(100) | |
59 random.shuffle(values) | |
60 | |
61 fifo = Fifo() | |
62 assert fifo.empty() | |
63 | |
64 for v in values: | |
65 fifo.append(v) | |
66 | |
67 got = [] | |
68 while not fifo.empty(): | |
69 got.append(fifo.pop()) | |
70 | |
71 assert got == values | |
72 | |
73 fifo.append(42) | |
74 assert fifo.pop() == 42 | |
75 assert fifo.empty() | |
76 | |
77 try: | |
78 fifo.pop() | |
79 except IndexError: | |
80 pass | |
81 else: | |
82 assert False |