{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Dynamic Array Exercise\n", "____\n", "\n", "In this exercise we will create our own Dynamic Array class!\n", "\n", "We'll be using a built in library called [ctypes](https://docs.python.org/2/library/ctypes.html). Check out the documentation for more info, but its basically going to be used here as a raw array from the ctypes module.\n", "If you find yourself very interested in it, check out: [Ctypes Tutorial](http://starship.python.net/crew/theller/ctypes/tutorial.html)\n", "\n", "Also..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**A quick note on public vs private methods, we can use an underscore _ before the method name to keep it non-public. For example:**" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class M(object):\n", " \n", " def public(self):\n", " print 'Use Tab to see me!'\n", " \n", " def _private(self):\n", " print \"You won't be able to Tab to see me!\"" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": true }, "outputs": [], "source": [ "m = M()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Use Tab to see me!\n" ] } ], "source": [ "m.public()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "You won't be able to see me!\n" ] } ], "source": [ "m._private()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Check out PEP 8 and the Python docs for more info on this!\n", "_____\n", "\n", "### Dynamic Array Implementation" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import ctypes\n", "\n", "class DynamicArray(object):\n", " '''\n", " DYNAMIC ARRAY CLASS (Similar to Python List)\n", " '''\n", " \n", " def __init__(self):\n", " self.n = 0 # Count actual elements (Default is 0)\n", " self.capacity = 1 # Default Capacity\n", " self.A = self.make_array(self.capacity)\n", " \n", " def __len__(self):\n", " \"\"\"\n", " Return number of elements sorted in array\n", " \"\"\"\n", " return self.n\n", " \n", " def __getitem__(self,k):\n", " \"\"\"\n", " Return element at index k\n", " \"\"\"\n", " if not 0 <= k