{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\">Functools module</h1>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from operator import add\n",
    "from functools import reduce\n",
    "\n",
    "print(list(reduce(add,\n",
    "                  [[1, 2, 3], [4, 5], [6], [7, 8, 9, 10]])))\n",
    "print(set(reduce(add,\n",
    "                  [[1, 2, 3], [4, 5], [6], [7, 8, 9, 10]],\n",
    "                  [0])))\n",
    "print(list(reduce(lambda x, y: [y, x],\n",
    "                  ((1, 2), (11, 12, 13), (21,), (31, 32, 33, 34), (41, 42, 43)))))\n",
    "print(tuple(reduce(lambda x, y: [y, x],\n",
    "                  ((1, 2), (11, 12, 13), (21,), (31, 32, 33, 34), (41, 42, 43)),\n",
    "                  (0,))))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from functools import cmp_to_key\n",
    "\n",
    "def cmp(x, y):\n",
    "    if x == y:\n",
    "        return 0\n",
    "    if x % 10 < y % 10 or x % 10 == y % 10 and x / 10 < y / 10:\n",
    "        return -1\n",
    "    return 1\n",
    "\n",
    "print(sorted([10, 11, 12, 20, 21, 22, 30, 31, 32], key = cmp_to_key(cmp)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from functools import namedtuple\n",
    "\n",
    "Point = namedtuple('Point', ['x', 'y', 'z'])\n",
    "p1 = Point(11, 12, 13)\n",
    "p2 = Point(21, z = 23, y = 22)\n",
    "print(p1)\n",
    "print(p2)\n",
    "print()\n",
    "\n",
    "print(p1[0], p1[1], p1[2])\n",
    "print(p2.x, p2.y, p2.z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from functools import partial\n",
    "\n",
    "def f(w, x, y, z, a, b, c, d):\n",
    "    print(w, x, y, z, a, b, c, d)\n",
    "    \n",
    "g = partial(f, 1, 2, b = 6,  d = 8)\n",
    "\n",
    "g(3, 4, c = 7, a = 5)"
   ]
  }
 ],
 "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": 0
}

Resource created Wednesday 16 September 2015, 11:45:48 AM.

file: functools_module.ipynb


Back to top

COMP9021 15s2 (Principles of Programming) is powered by WebCMS3
CRICOS Provider No. 00098G