Created
June 19, 2017 00:33
-
-
Save zmarvel/4e4478c72d49c8e7f1e73c63e2429257 to your computer and use it in GitHub Desktop.
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
# Implement a queue with 2 stacks . Your queue should have an enqueue and a | |
# dequeue function and it should be "first in first out" (FIFO). | |
# | |
# Optimize for the time cost of mmm function calls on your queue. These can be | |
# any mix of enqueue and dequeue calls. | |
# | |
# Assume you already have a stack implementation and it gives O(1) | |
# time push and pop. | |
class Stack(list): | |
def push(self, obj): | |
self.append(obj) | |
def pop(self): | |
return super().pop() | |
class Queue(): | |
def __init__(self): | |
self._stack0 = Stack() | |
self._stack1 = Stack() | |
def enqueue(self, obj): | |
self._stack0.push(obj) | |
def dequeue(self): | |
if len(self._stack1) == 0: | |
while len(self._stack0) > 0: | |
self._stack1.push(self._stack0.pop()) | |
return self._stack1.pop() | |
if __name__ == '__main__': | |
q = Queue() | |
q.enqueue(1) | |
q.enqueue(2) | |
assert q.dequeue() == 1 | |
q.enqueue(3) | |
q.enqueue(4) | |
assert q.dequeue() == 2 | |
assert q.dequeue() == 3 | |
assert q.dequeue() == 4 | |
q.enqueue(3) | |
q.enqueue(4) | |
assert q.dequeue() == 3 | |
assert q.dequeue() == 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment