{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Implementation of Queue\n", "\n", "In this lecture we will build on our previous understanding of Queues by implementing our own class of Queue!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "____\n", "## Queue Methods and Attributes\n", "\n", "\n", "Before we begin implementing our own queue, let's review the attribute and methods it will have:\n", "\n", "* Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue.\n", "* enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing.\n", "* dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified.\n", "* isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value.\n", "* size() returns the number of items in the queue. It needs no parameters and returns an integer." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "____\n", "## Queue Implementation" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Queue:\n", " def __init__(self):\n", " self.items = []\n", "\n", " def isEmpty(self):\n", " return self.items == []\n", "\n", " def enqueue(self, item):\n", " self.items.insert(0,item)\n", "\n", " def dequeue(self):\n", " return self.items.pop()\n", "\n", " def size(self):\n", " return len(self.items)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "q = Queue()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "q.size()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "q.isEmpty()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "q.enqueue(1)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "q.dequeue()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Good Job!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }