{ "metadata": { "name": "", "signature": "sha256:159f3efd0322a17a2826231fee1a98dd46c11d7e2fda169bb15cffde762539ff" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Cartesian Product\n", "\n", "- **Author:** [Chris Albon](http://www.chrisalbon.com/), [@ChrisAlbon](https://twitter.com/chrisalbon)\n", "- **Date:** -\n", "- **Repo:** [Python 3 code snippets for data science](https://github.com/chrisalbon/code_py)\n", "- **Note:**" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# import pandas as pd\n", "import pandas as pd" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "# Create two lists\n", "i = [1,2,3,4,5]\n", "j = [1,2,3,4,5]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "# List every single x in i with every single y (i.e. Cartesian product)\n", "[(x, y) for x in i for y in j]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 14, "text": [ "[(1, 1),\n", " (1, 2),\n", " (1, 3),\n", " (1, 4),\n", " (1, 5),\n", " (2, 1),\n", " (2, 2),\n", " (2, 3),\n", " (2, 4),\n", " (2, 5),\n", " (3, 1),\n", " (3, 2),\n", " (3, 3),\n", " (3, 4),\n", " (3, 5),\n", " (4, 1),\n", " (4, 2),\n", " (4, 3),\n", " (4, 4),\n", " (4, 5),\n", " (5, 1),\n", " (5, 2),\n", " (5, 3),\n", " (5, 4),\n", " (5, 5)]" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "# An alternative way to do the cartesian product\n", "\n", "# import itertools\n", "import itertools\n", "\n", "# for two sets, find the the cartisan product\n", "for i in itertools.product([1,2,3,4,5], [1,2,3,4,5]):\n", " # and print it\n", " print(i)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1, 1)\n", "(1, 2)\n", "(1, 3)\n", "(1, 4)\n", "(1, 5)\n", "(2, 1)\n", "(2, 2)\n", "(2, 3)\n", "(2, 4)\n", "(2, 5)\n", "(3, 1)\n", "(3, 2)\n", "(3, 3)\n", "(3, 4)\n", "(3, 5)\n", "(4, 1)\n", "(4, 2)\n", "(4, 3)\n", "(4, 4)\n", "(4, 5)\n", "(5, 1)\n", "(5, 2)\n", "(5, 3)\n", "(5, 4)\n", "(5, 5)\n" ] } ], "prompt_number": 16 } ], "metadata": {} } ] }