Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## the problem is that implement queue with the enqueue() and dequeue() operations with stacks"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 1,
- "metadata": {},
- "outputs": [],
- "source": [
- "class Queue:\n",
- " \n",
- " def __init__(self):\n",
- " self.dequeue_stack = []\n",
- " self.enqueue_stack = []\n",
- " \n",
- " def enqueue(self, data):\n",
- " self.enqueue_stack.append(data)\n",
- " \n",
- " def dequeue(self):\n",
- " if not self.enqueue_stack and not self.dequeue_stack:\n",
- " raise Exception('Stacks are empty')\n",
- " \n",
- " # if dequeue stack is empty, add all item\n",
- " if not self.dequeue_stack:\n",
- " while self.enqueue_stack:\n",
- " self.dequeue_stack.append(self.enqueue_stack.pop())\n",
- " \n",
- " return self.dequeue_stack.pop()"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "q = Queue()\n",
- "q.enqueue(1)\n",
- "q.enqueue(2)\n",
- "q.enqueue(3)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {},
- "outputs": [
- {
- "data": {
- "text/plain": [
- "1"
- ]
- },
- "execution_count": 3,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "q.dequeue()"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.5.2"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
- }
Add Comment
Please, Sign In to add comment