{ "metadata": { "name": "", "signature": "sha256:91b230d6c40eec734e6eb9aae5b1d697914107974522d5a5815a24255f520d43" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Recursive Functions\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": "markdown", "metadata": {}, "source": [ "## Simple factorial" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(5*4*3*2*1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "120\n" ] } ], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Recursive function\n", "\n", "The tell-tale sign of a recursive function is a function that calls itself" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Create a function inputing n, that,\n", "def factorial(n):\n", " # if n is less than or equal to 1,\n", " if n <= 1:\n", " # return n,\n", " return n\n", "\n", " # if not, return n multiplied by the output\n", " # of the factorial function of one less than n\n", " return n*factorial(n-1)\n", "\n", "# run the function\n", "factorial(5)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 31, "text": [ "120" ] } ], "prompt_number": 31 } ], "metadata": {} } ] }