Guest User

Untitled

a guest
Dec 19th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "## the problem is that implement queue with the enqueue() and dequeue() operations with stacks"
  8. ]
  9. },
  10. {
  11. "cell_type": "code",
  12. "execution_count": 1,
  13. "metadata": {},
  14. "outputs": [],
  15. "source": [
  16. "class Queue:\n",
  17. " \n",
  18. " def __init__(self):\n",
  19. " self.dequeue_stack = []\n",
  20. " self.enqueue_stack = []\n",
  21. " \n",
  22. " def enqueue(self, data):\n",
  23. " self.enqueue_stack.append(data)\n",
  24. " \n",
  25. " def dequeue(self):\n",
  26. " if not self.enqueue_stack and not self.dequeue_stack:\n",
  27. " raise Exception('Stacks are empty')\n",
  28. " \n",
  29. " # if dequeue stack is empty, add all item\n",
  30. " if not self.dequeue_stack:\n",
  31. " while self.enqueue_stack:\n",
  32. " self.dequeue_stack.append(self.enqueue_stack.pop())\n",
  33. " \n",
  34. " return self.dequeue_stack.pop()"
  35. ]
  36. },
  37. {
  38. "cell_type": "code",
  39. "execution_count": 2,
  40. "metadata": {},
  41. "outputs": [],
  42. "source": [
  43. "q = Queue()\n",
  44. "q.enqueue(1)\n",
  45. "q.enqueue(2)\n",
  46. "q.enqueue(3)"
  47. ]
  48. },
  49. {
  50. "cell_type": "code",
  51. "execution_count": 3,
  52. "metadata": {},
  53. "outputs": [
  54. {
  55. "data": {
  56. "text/plain": [
  57. "1"
  58. ]
  59. },
  60. "execution_count": 3,
  61. "metadata": {},
  62. "output_type": "execute_result"
  63. }
  64. ],
  65. "source": [
  66. "q.dequeue()"
  67. ]
  68. }
  69. ],
  70. "metadata": {
  71. "kernelspec": {
  72. "display_name": "Python 3",
  73. "language": "python",
  74. "name": "python3"
  75. },
  76. "language_info": {
  77. "codemirror_mode": {
  78. "name": "ipython",
  79. "version": 3
  80. },
  81. "file_extension": ".py",
  82. "mimetype": "text/x-python",
  83. "name": "python",
  84. "nbconvert_exporter": "python",
  85. "pygments_lexer": "ipython3",
  86. "version": "3.5.2"
  87. }
  88. },
  89. "nbformat": 4,
  90. "nbformat_minor": 2
  91. }
Add Comment
Please, Sign In to add comment