Created
February 18, 2012 22:30
-
-
Save majek/1861202 to your computer and use it in GitHub Desktop.
Simplistic Queue implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Very simple queue implementation. Don't use it. Use collections.deque | |
instead. | |
>>> q = Queue() | |
>>> q.push(1) | |
>>> q.push(2) | |
>>> len(q) | |
2 | |
>>> bool(q) | |
True | |
>>> q.pop() | |
1 | |
>>> q.push(3) | |
>>> len(q) | |
2 | |
>>> q.pop() | |
2 | |
>>> q.push(4) | |
>>> q.pop() | |
3 | |
>>> q.pop() | |
4 | |
>>> len(q) | |
0 | |
>>> bool(q) | |
False | |
>>> q.pop() | |
Traceback (most recent call last): | |
... | |
IndexError: pop from empty list | |
''' | |
class Queue(object): | |
def __init__(self): | |
self.f, self.b = [], [] | |
def push(self, e): | |
self.b.append(e) | |
def pop(self): | |
if not self.f and self.b: | |
self.b.reverse() | |
self.f, self.b = self.b, [] | |
return self.f.pop() | |
def __len__(self): | |
return len(self.f + self.b) | |
def __nonzero__(self): | |
return bool(len(self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment