Skip to content

Instantly share code, notes, and snippets.

@majek
Created February 18, 2012 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save majek/1861202 to your computer and use it in GitHub Desktop.
Save majek/1861202 to your computer and use it in GitHub Desktop.
Simplistic Queue implementation
'''
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