{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Solution Notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem: Implement a queue with enqueue and dequeue methods using a linked list.\n", "\n", "* [Constraints](#Constraints)\n", "* [Test Cases](#Test-Cases)\n", "* [Algorithm](#Algorithm)\n", "* [Code](#Code)\n", "* [Unit Test](#Unit-Test)\n", "* [Pythonic-Code](#Pythonic-Code)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Constraints\n", "\n", "* If there is one item in the list, do you expect the head and tail pointers to both point to it?\n", " * Yes\n", "* If there are no items on the list, do you expect the head and tail pointers to be None?\n", " * Yes\n", "* If you dequeue on an empty queue, does that return None?\n", " * Yes\n", "* Can we assume this fits memory?\n", " * Yes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test Cases\n", "\n", "### Enqueue\n", "\n", "* Enqueue to an empty queue\n", "* Enqueue to a non-empty queue\n", "\n", "### Dequeue\n", "\n", "* Dequeue an empty queue -> None\n", "* Dequeue a queue with one element\n", "* Dequeue a queue with more than one element" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Algorithm\n", "\n", "### Enqueue\n", "\n", "* If the list is empty, set head and tail to node\n", "* Else, set tail to node\n", "\n", "Complexity:\n", "* Time: O(1)\n", "* Space: O(1)\n", "\n", "### Dequeue\n", "\n", "* If the list is empty, return None\n", "* If the list has one node\n", " * Save the head node's value\n", " * Set head and tail to None\n", " * Return the saved value\n", "* Else\n", " * Save the head node's value\n", " * Set head to its next node\n", " * Return the saved value\n", "\n", "Complexity:\n", "* Time: O(1)\n", "* Space: O(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting queue_list.py\n" ] } ], "source": [ "%%writefile queue_list.py\n", "class Node(object):\n", "\n", " def __init__(self, data):\n", " self.data = data\n", " self.next = None\n", "\n", "\n", "class Queue(object):\n", "\n", " def __init__(self):\n", " self.head = None\n", " self.tail = None\n", "\n", " def enqueue(self, data):\n", " node = Node(data)\n", " # Empty list\n", " if self.head is None and self.tail is None:\n", " self.head = node\n", " self.tail = node\n", " else:\n", " self.tail.next = node\n", " self.tail = node\n", "\n", " def dequeue(self):\n", " # Empty list\n", " if self.head is None and self.tail is None:\n", " return None\n", " data = self.head.data\n", " # Remove only element from a one element list\n", " if self.head == self.tail:\n", " self.head = None\n", " self.tail = None\n", " else:\n", " self.head = self.head.next\n", " return data" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "%run queue_list.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unit Test\n", "\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting test_queue_list.py\n" ] } ], "source": [ "%%writefile test_queue_list.py\n", "import unittest\n", "\n", "\n", "class TestQueue(unittest.TestCase):\n", "\n", " # TODO: It would be better if we had unit tests for each\n", " # method in addition to the following end-to-end test\n", " def test_end_to_end(self):\n", " print('Test: Dequeue an empty queue')\n", " queue = Queue()\n", " self.assertEqual(queue.dequeue(), None)\n", "\n", " print('Test: Enqueue to an empty queue')\n", " queue.enqueue(1)\n", "\n", " print('Test: Dequeue a queue with one element')\n", " self.assertEqual(queue.dequeue(), 1)\n", "\n", " print('Test: Enqueue to a non-empty queue')\n", " queue.enqueue(2)\n", " queue.enqueue(3)\n", " queue.enqueue(4)\n", "\n", " print('Test: Dequeue a queue with more than one element')\n", " self.assertEqual(queue.dequeue(), 2)\n", " self.assertEqual(queue.dequeue(), 3)\n", " self.assertEqual(queue.dequeue(), 4)\n", "\n", " print('Success: test_end_to_end')\n", "\n", "\n", "def main():\n", " test = TestQueue()\n", " test.test_end_to_end()\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Test: Dequeue an empty queue\n", "Test: Enqueue to an empty queue\n", "Test: Dequeue a queue with one element\n", "Test: Enqueue to a non-empty queue\n", "Test: Dequeue a queue with more than one element\n", "Success: test_end_to_end\n" ] } ], "source": [ "%run -i test_queue_list.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pythonic-Code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Source: https://docs.python.org/2/tutorial/datastructures.html#using-lists-as-queues\n", "
\n",
    "It is possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).\n",
    "\n",
    "To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:\n",
    "\n",
    ">>>\n",
    ">>> from collections import deque\n",
    ">>> queue = deque([\"Eric\", \"John\", \"Michael\"])\n",
    ">>> queue.append(\"Terry\")           # Terry arrives\n",
    ">>> queue.append(\"Graham\")          # Graham arrives\n",
    ">>> queue.popleft()                 # The first to arrive now leaves\n",
    "'Eric'\n",
    ">>> queue.popleft()                 # The second to arrive now leaves\n",
    "'John'\n",
    ">>> queue                           # Remaining queue in order of arrival\n",
    "deque(['Michael', 'Terry', 'Graham'])\n",
    "
" ] } ], "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.7.2" } }, "nbformat": 4, "nbformat_minor": 1 }