{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Cortex-A9 programming in Python"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We show here an example of how to run Python with Pynq. Python is running exclusively on the ARM Cortex-A9 processor. This example, which is based on calculating the factors and primes of integer numbers, give us a sense of the performance available when running on a 650MHz ARM Cortex-A9 dual core processor running Linux.\n",
    "\n",
    "## The factors and primes example\n",
    "Code is provided in the cell below for a function to calculate factors and primes. It contains some sample functions to calculate the factors and primes of integers. We will use three functions from the factors_and_primes module to demonstrate Python programming. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "\"\"\"Factors-and-primes functions.\n",
    "\n",
    "Find factors or primes of integers, int ranges and int lists\n",
    "and sets of integers with most factors in a given integer interval\n",
    "\n",
    "\"\"\"\n",
    "\n",
    "from pprint import pprint\n",
    "\n",
    "def factorize(n):\n",
    "    \"\"\"Calculate all factors of integer n.\n",
    "        \n",
    "    Parameters\n",
    "    ----------\n",
    "    n : int\n",
    "        integer to factorize.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    list\n",
    "        A sorted set of integer factors of n.\n",
    "        \n",
    "    \"\"\"\n",
    "    factors = []\n",
    "    if isinstance(n, int) and n > 0:\n",
    "        if n == 1:\n",
    "            factors.append(n)\n",
    "            return factors\n",
    "        else:\n",
    "            for x in range(1, int(n**0.5)+1):\n",
    "                if n % x == 0:\n",
    "                    factors.append(x)\n",
    "                    factors.append(n//x)\n",
    "            return sorted(set(factors))\n",
    "    else:\n",
    "        print('factorize ONLY computes with one integer argument > 0')\n",
    "\n",
    "\n",
    "def primes_between(interval_min, interval_max):\n",
    "    \"\"\"Find all primes in the interval.\n",
    "    \n",
    "    The interval is defined by interval_min and interval_max.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    interval_min : int\n",
    "        Start of the integer range.\n",
    "    interval_max : int\n",
    "        End of the integer range.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    list\n",
    "        A sorted set of integer primes in original range.\n",
    "        \n",
    "    \"\"\"\n",
    "    primes = []\n",
    "    if (isinstance(interval_min, int) and interval_min > 0 and \n",
    "       isinstance(interval_max, int) and interval_max > interval_min):\n",
    "        if interval_min == 1:\n",
    "            primes = [1]\n",
    "        for i in range(interval_min, interval_max):\n",
    "            if len(factorize(i)) == 2:\n",
    "                primes.append(i)\n",
    "        return sorted(primes)\n",
    "    else:\n",
    "        print('primes_between ONLY computes over the specified range.')\n",
    "\n",
    "        \n",
    "def primes_in(integer_list):\n",
    "    \"\"\"Calculate all unique prime numbers.\n",
    "    \n",
    "    Calculate the prime numbers in a list of integers.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    integer_list : list\n",
    "        A list of integers to test for primality.\n",
    "        \n",
    "    Returns\n",
    "    -------\n",
    "    list\n",
    "        A sorted set of integer primes from original list.\n",
    "    \n",
    "    \"\"\"\n",
    "    primes = []\n",
    "    try:\n",
    "        for i in (integer_list):\n",
    "            if len(factorize(i)) == 2:\n",
    "                primes.append(i)\n",
    "        return sorted(set(primes))\n",
    "    except TypeError:\n",
    "        print('primes_in ONLY computes over lists of integers.')\n",
    "\n",
    "\n",
    "def get_ints_with_most_factors(interval_min, interval_max):\n",
    "    \"\"\"Finds the integers with the most factors.\n",
    "    \n",
    "    Find the integer or integers with the most factors in a given \n",
    "    integer range.\n",
    "    \n",
    "    The returned result is a list of tuples, where each tuple is:\n",
    "    [no_with_most_factors (int), no_of_factors (int), \n",
    "    factors (int list)].\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    interval_min : int\n",
    "        Start of the integer range.\n",
    "    interval_max : int\n",
    "        End of the integer range.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    list\n",
    "        A list of tuples showing the results.\n",
    "        \n",
    "    \"\"\"\n",
    "    max_no_of_factors = 1\n",
    "    all_ints_with_most_factors = []\n",
    "    \n",
    "    #: Find the lowest number with most factors between i_min and i_max\n",
    "    if interval_check(interval_min, interval_max):\n",
    "        for i in range(interval_min, interval_max):\n",
    "            factors_of_i = factorize(i)\n",
    "            no_of_factors = len(factors_of_i) \n",
    "            if no_of_factors > max_no_of_factors:\n",
    "                max_no_of_factors = no_of_factors\n",
    "                results = (i, max_no_of_factors, factors_of_i,\\\n",
    "                            primes_in(factors_of_i))\n",
    "        all_ints_with_most_factors.append(results)\n",
    "    \n",
    "        #: Find any larger numbers with an equal number of factors\n",
    "        for i in range(all_ints_with_most_factors[0][0]+1, interval_max):\n",
    "            factors_of_i = factorize(i)\n",
    "            no_of_factors = len(factors_of_i) \n",
    "            if no_of_factors == max_no_of_factors:\n",
    "                results = (i, max_no_of_factors, factors_of_i, \\\n",
    "                            primes_in(factors_of_i))\n",
    "                all_ints_with_most_factors.append(results)\n",
    "        return all_ints_with_most_factors       \n",
    "    else:\n",
    "        print_error_msg() \n",
    "\n",
    "            \n",
    "def print_ints_with_most_factors(interval_min, interval_max):\n",
    "    \"\"\"Reports integers with most factors in a given integer range.\n",
    "    \n",
    "    The results can consist of the following: \n",
    "    1.  All the integers with the most factors\n",
    "    2.  The number of factors\n",
    "    3.  The actual factors of each of the integers\n",
    "    4.  Any prime numbers in the list of factors\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    interval_min : int\n",
    "        Start of the integer range.\n",
    "    interval_max : int\n",
    "        End of the integer range.\n",
    "        \n",
    "    Returns\n",
    "    -------\n",
    "    list\n",
    "        A list of tuples showing the integers and factors.\n",
    "        \n",
    "    \"\"\"\n",
    "    if interval_check(interval_min, interval_max):\n",
    "        print('\\nBetween {} and {} the number/s with the most factors:\\n'.\n",
    "           format(interval_min, interval_max))\n",
    "        for results in (get_ints_with_most_factors(\n",
    "                            interval_min, interval_max)):\n",
    "            print('{} ... with the following {} factors:'\n",
    "                      .format(results[0], results[1]))\n",
    "            pprint(results[2])\n",
    "            print('The prime number factors of {} are:'\n",
    "                      .format(results[0]))\n",
    "            pprint(results[3])\n",
    "    else:\n",
    "        print_error_msg()\n",
    "\n",
    "        \n",
    "def interval_check(interval_min, interval_max):\n",
    "    \"\"\"Check type and range of integer interval.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    interval_min : int\n",
    "        Start of the integer range.\n",
    "    interval_max : int\n",
    "        End of the integer range.\n",
    "        \n",
    "    Returns\n",
    "    -------\n",
    "    None\n",
    "    \n",
    "    \"\"\"\n",
    "    if (isinstance(interval_min, int) and interval_min > 0 and \n",
    "       isinstance(interval_max, int) and interval_max > interval_min):\n",
    "        return True\n",
    "    else:\n",
    "        return False\n",
    "\n",
    "def print_error_msg():\n",
    "    \"\"\"Print invalid integer interval error message.\n",
    "    \n",
    "    Returns\n",
    "    -------\n",
    "    None\n",
    "    \n",
    "    \"\"\"\n",
    "    print('ints_with_most_factors ONLY computes over integer intervals where'\n",
    "            ' interval_min <= int_with_most_factors < interval_max and'\n",
    "            ' interval_min >= 1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we will call the factorize() function to calculate the factors of an integer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 13, 26, 41, 82, 533, 1066]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "factorize(1066)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The primes_between() function can tell us how many prime numbers there are in an integer range. Let’s try it for the interval 1 through 1066.  We can also use one of Python’s built-in methods len() to count them all."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "180"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(primes_between(1, 1066))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, we can combine len() with another built-in method, sum(), to calculate the average of the 180 prime numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "486.2055555555556"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "primes_1066 = primes_between(1, 1066)\n",
    "primes_1066_average = sum(primes_1066) / len(primes_1066)\n",
    "primes_1066_average"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This result makes sense intuitively because prime numbers are known to become less frequent for larger number intervals. These examples demonstrate how Python treats functions as first-class objects so that functions may be passed as parameters to other functions. This is a key property of functional programming and demonstrates the power of Python.\n",
    "\n",
    "In the next code snippet, we can use list comprehensions (a ‘Pythonic’ form of the map-filter-reduce template) to ‘mine’ the factors of 1066 to find those factors that end in the digit ‘3’."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3,\n",
       " 13,\n",
       " 23,\n",
       " 43,\n",
       " 53,\n",
       " 73,\n",
       " 83,\n",
       " 103,\n",
       " 113,\n",
       " 163,\n",
       " 173,\n",
       " 193,\n",
       " 223,\n",
       " 233,\n",
       " 263,\n",
       " 283,\n",
       " 293,\n",
       " 313,\n",
       " 353,\n",
       " 373,\n",
       " 383,\n",
       " 433,\n",
       " 443,\n",
       " 463,\n",
       " 503,\n",
       " 523,\n",
       " 563,\n",
       " 593,\n",
       " 613,\n",
       " 643,\n",
       " 653,\n",
       " 673,\n",
       " 683,\n",
       " 733,\n",
       " 743,\n",
       " 773,\n",
       " 823,\n",
       " 853,\n",
       " 863,\n",
       " 883,\n",
       " 953,\n",
       " 983,\n",
       " 1013,\n",
       " 1033,\n",
       " 1063]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "primes_1066_ends3 = [x for x in primes_between(1, 1066) if str(x).endswith('3')]\n",
    "primes_1066_ends3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This code tells Python to first convert each prime between 1 and 1066 to a string and then to return those numbers whose string representation end with the number ‘3’. It uses the built-in str() and endswith() methods to test each prime for inclusion in the list.\n",
    "\n",
    "And because we really want to know what fraction of the 180 primes of 1066 end in a ‘3’, we can calculate ..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.25"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(primes_1066_ends3) / len(primes_1066)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These examples demonstrate how Python is a modern, multi-paradigmatic language. More simply, it continually integrates the best features of other leading languages, including functional programming constructs. Consider how many lines of code you would need to implement the list comprehension above in C and you get an appreciation of the power of productivity-layer languages. Higher levels of programming abstraction really do result in higher programmer productivity!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## More intensive calculations\n",
    "To stress the ARM processor a little more, we will run a script to determine the integer number, or numbers, that have the most factors between 1 and 1066, using the print_ints_with_most_factors() function from the factors_and_primes module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Between 1 and 1066 the number/s with the most factors:\n",
      "\n",
      "840 ... with the following 32 factors:\n",
      "[1,\n",
      " 2,\n",
      " 3,\n",
      " 4,\n",
      " 5,\n",
      " 6,\n",
      " 7,\n",
      " 8,\n",
      " 10,\n",
      " 12,\n",
      " 14,\n",
      " 15,\n",
      " 20,\n",
      " 21,\n",
      " 24,\n",
      " 28,\n",
      " 30,\n",
      " 35,\n",
      " 40,\n",
      " 42,\n",
      " 56,\n",
      " 60,\n",
      " 70,\n",
      " 84,\n",
      " 105,\n",
      " 120,\n",
      " 140,\n",
      " 168,\n",
      " 210,\n",
      " 280,\n",
      " 420,\n",
      " 840]\n",
      "The prime number factors of 840 are:\n",
      "[2, 3, 5, 7]\n"
     ]
    }
   ],
   "source": [
    "print_ints_with_most_factors(1, 1066)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ARM processor remains quite responsive. Running this for much larger numbers, say 50,000, will demonstrate noticeably slower responses as we would expect.\n",
    "\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.4.3+"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
