queue implemented with a pair of stacks
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
class staq: | |
def __init__(self, stack = []): | |
self.enqstk = stack | |
self.deqstk = [] | |
def _swap(self): | |
if len(self.deqstk) == 0: | |
while len(self.enqstk) > 0: | |
_pus(self.deqstk, _pop(self.enqstk)) | |
def enq(self, item): | |
_pus(self.enqstk, item) | |
def deq(self): | |
self._swap() | |
return _pop(self.deqstk) | |
def __str__(self): | |
return "%s -> %s" % (self.enqstk,self.deqstk) | |
def __repr__(self): | |
return str(self) | |
def _pop(stack): | |
out = stack[-1] | |
stack[:] = stack[:-1] | |
return out | |
def _pus(stack, item): | |
stack += [item] | |
if __name__ == "__main__": | |
q = staq([1,2,3]) | |
print("q = staq([1,2,3]) : %s" % (q,)) | |
print("q.deq() -> %s : %s" % (q.deq(), q)) | |
q.enq(4) | |
print("q.enq(4) : %s" % (q,)) | |
print("q.deq() -> %s : %s" % (q.deq(), q)) | |
print("q.deq() -> %s : %s" % (q.deq(), q)) | |
print("q.deq() -> %s : %s" % (q.deq(), q)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment