{ "cells": [ { "cell_type": "markdown", "id": "fb222164", "metadata": {}, "source": [ "\n", "\n", "
\n", " \n", " \"QuantEcon\"\n", " \n", "
" ] }, { "cell_type": "markdown", "id": "4a0f5e81", "metadata": {}, "source": [ "# Functions\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "61b62b06", "metadata": {}, "source": [ "## Contents\n", "\n", "- [Functions](#Functions) \n", " - [Overview](#Overview) \n", " - [Function Basics](#Function-Basics) \n", " - [Defining Functions](#Defining-Functions) \n", " - [Applications](#Applications) \n", " - [Recursive Function Calls (Advanced)](#Recursive-Function-Calls-%28Advanced%29) \n", " - [Exercises](#Exercises) \n", " - [Advanced Exercises](#Advanced-Exercises) " ] }, { "cell_type": "markdown", "id": "9a1b3c59", "metadata": {}, "source": [ "## Overview\n", "\n", "Functions are an extremely useful construct provided by almost all programming.\n", "\n", "We have already met several functions, such as\n", "\n", "- the `sqrt()` function from NumPy and \n", "- the built-in `print()` function \n", "\n", "\n", "In this lecture we’ll\n", "\n", "1. treat functions systematically and cover syntax and use-cases, and \n", "1. learn to do is build our own user-defined functions. \n", "\n", "\n", "We will use the following imports." ] }, { "cell_type": "code", "execution_count": null, "id": "69148ee8", "metadata": { "hide-output": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "id": "702b5fb1", "metadata": {}, "source": [ "## Function Basics\n", "\n", "A function is a named section of a program that implements a specific task.\n", "\n", "Many functions exist already and we can use them as is.\n", "\n", "First we review these functions and then discuss how we can build our own." ] }, { "cell_type": "markdown", "id": "3eddb503", "metadata": {}, "source": [ "### Built-In Functions\n", "\n", "Python has a number of **built-in** functions that are available without `import`.\n", "\n", "We have already met some" ] }, { "cell_type": "code", "execution_count": null, "id": "92090fab", "metadata": { "hide-output": false }, "outputs": [], "source": [ "max(19, 20)" ] }, { "cell_type": "code", "execution_count": null, "id": "9dde3fe7", "metadata": { "hide-output": false }, "outputs": [], "source": [ "print('foobar')" ] }, { "cell_type": "code", "execution_count": null, "id": "f961a9fb", "metadata": { "hide-output": false }, "outputs": [], "source": [ "str(22)" ] }, { "cell_type": "code", "execution_count": null, "id": "35a626b6", "metadata": { "hide-output": false }, "outputs": [], "source": [ "type(22)" ] }, { "cell_type": "markdown", "id": "62683df5", "metadata": {}, "source": [ "The full list of Python built-ins is [here](https://docs.python.org/library/functions.html)." ] }, { "cell_type": "markdown", "id": "80f86869", "metadata": {}, "source": [ "### Third Party Functions\n", "\n", "If the built-in functions don’t cover what we need, we either need to import\n", "functions or create our own.\n", "\n", "Examples of importing and using functions were given in the [previous lecture](https://python-programming.quantecon.org/python_by_example.html)\n", "\n", "Here’s another one, which tests whether a given year is a leap year:" ] }, { "cell_type": "code", "execution_count": null, "id": "2bedf5bc", "metadata": { "hide-output": false }, "outputs": [], "source": [ "import calendar\n", "calendar.isleap(2024)" ] }, { "cell_type": "markdown", "id": "16663ae5", "metadata": {}, "source": [ "## Defining Functions\n", "\n", "In many instances it’s useful to be able to define our own functions.\n", "\n", "Let’s start by discussing how it’s done." ] }, { "cell_type": "markdown", "id": "1281e76f", "metadata": {}, "source": [ "### Basic Syntax\n", "\n", "Here’s a very simple Python function, that implements the mathematical function $ f(x) = 2 x + 1 $" ] }, { "cell_type": "code", "execution_count": null, "id": "dcb59167", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def f(x):\n", " return 2 * x + 1" ] }, { "cell_type": "markdown", "id": "fcedcd79", "metadata": {}, "source": [ "Now that we’ve defined this function, let’s *call* it and check whether it does what we expect:" ] }, { "cell_type": "code", "execution_count": null, "id": "abecded8", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f(1) " ] }, { "cell_type": "code", "execution_count": null, "id": "6e193038", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f(10)" ] }, { "cell_type": "markdown", "id": "cc2ba8a6", "metadata": {}, "source": [ "Here’s a longer function, that computes the absolute value of a given number.\n", "\n", "(Such a function already exists as a built-in, but let’s write our own for the\n", "exercise.)" ] }, { "cell_type": "code", "execution_count": null, "id": "db7509fd", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def new_abs_function(x):\n", " if x < 0:\n", " abs_value = -x\n", " else:\n", " abs_value = x\n", " return abs_value" ] }, { "cell_type": "markdown", "id": "e482e82e", "metadata": {}, "source": [ "Let’s review the syntax here.\n", "\n", "- `def` is a Python keyword used to start function definitions. \n", "- `def new_abs_function(x):` indicates that the function is called `new_abs_function` and that it has a single argument `x`. \n", "- The indented code is a code block called the *function body*. \n", "- The `return` keyword indicates that `abs_value` is the object that should be returned to the calling code. \n", "\n", "\n", "This whole function definition is read by the Python interpreter and stored in memory.\n", "\n", "Let’s call it to check that it works:" ] }, { "cell_type": "code", "execution_count": null, "id": "55ec1f5f", "metadata": { "hide-output": false }, "outputs": [], "source": [ "print(new_abs_function(3))\n", "print(new_abs_function(-3))" ] }, { "cell_type": "markdown", "id": "ff3c14b3", "metadata": {}, "source": [ "Note that a function can have arbitrarily many `return` statements (including zero).\n", "\n", "Execution of the function terminates when the first return is hit, allowing\n", "code like the following example" ] }, { "cell_type": "code", "execution_count": null, "id": "5ce7ad47", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def f(x):\n", " if x < 0:\n", " return 'negative'\n", " return 'nonnegative'" ] }, { "cell_type": "markdown", "id": "5ccdbeb9", "metadata": {}, "source": [ "(Writing functions with multiple return statements is typically discouraged, as\n", "it can make logic hard to follow.)\n", "\n", "Functions without a return statement automatically return the special Python object `None`.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "fa519f22", "metadata": {}, "source": [ "### Keyword Arguments\n", "\n", "\n", "\n", "In a [previous lecture](https://python-programming.quantecon.org/python_by_example.html#python-by-example), you came across the statement" ] }, { "cell_type": "markdown", "id": "78d8a0ee", "metadata": { "hide-output": false }, "source": [ "```python3\n", "plt.plot(x, 'b-', label=\"white noise\")\n", "```\n" ] }, { "cell_type": "markdown", "id": "82d4170e", "metadata": {}, "source": [ "In this call to Matplotlib’s `plot` function, notice that the last argument is passed in `name=argument` syntax.\n", "\n", "This is called a *keyword argument*, with `label` being the keyword.\n", "\n", "Non-keyword arguments are called *positional arguments*, since their meaning\n", "is determined by order\n", "\n", "- `plot(x, 'b-')` differs from `plot('b-', x)` \n", "\n", "\n", "Keyword arguments are particularly useful when a function has a lot of arguments, in which case it’s hard to remember the right order.\n", "\n", "You can adopt keyword arguments in user-defined functions with no difficulty.\n", "\n", "The next example illustrates the syntax" ] }, { "cell_type": "code", "execution_count": null, "id": "5c36422c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def f(x, a=1, b=1):\n", " return a + b * x" ] }, { "cell_type": "markdown", "id": "bb5c1702", "metadata": {}, "source": [ "The keyword argument values we supplied in the definition of `f` become the default values" ] }, { "cell_type": "code", "execution_count": null, "id": "edecca8d", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f(2)" ] }, { "cell_type": "markdown", "id": "e5f138d0", "metadata": {}, "source": [ "They can be modified as follows" ] }, { "cell_type": "code", "execution_count": null, "id": "5839ea1f", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f(2, a=4, b=5)" ] }, { "cell_type": "markdown", "id": "430428cd", "metadata": {}, "source": [ "### The Flexibility of Python Functions\n", "\n", "As we discussed in the [previous lecture](https://python-programming.quantecon.org/python_by_example.html#python-by-example), Python functions are very flexible.\n", "\n", "In particular\n", "\n", "- Any number of functions can be defined in a given file. \n", "- Functions can be (and often are) defined inside other functions. \n", "- Any object can be passed to a function as an argument, including other functions. \n", "- A function can return any kind of object, including functions. \n", "\n", "\n", "We will give examples of how straightforward it is to pass a function to\n", "a function in the following sections." ] }, { "cell_type": "markdown", "id": "41aa8f24", "metadata": {}, "source": [ "### One-Line Functions: `lambda`\n", "\n", "\n", "\n", "The `lambda` keyword is used to create simple functions on one line.\n", "\n", "For example, the definitions" ] }, { "cell_type": "code", "execution_count": null, "id": "6e43d52f", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def f(x):\n", " return x**3" ] }, { "cell_type": "markdown", "id": "b753576f", "metadata": {}, "source": [ "and" ] }, { "cell_type": "code", "execution_count": null, "id": "fba01a5c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f = lambda x: x**3" ] }, { "cell_type": "markdown", "id": "861834a1", "metadata": {}, "source": [ "are entirely equivalent.\n", "\n", "To see why `lambda` is useful, suppose that we want to calculate $ \\int_0^2 x^3 dx $ (and have forgotten our high-school calculus).\n", "\n", "The SciPy library has a function called `quad` that will do this calculation for us.\n", "\n", "The syntax of the `quad` function is `quad(f, a, b)` where `f` is a function and `a` and `b` are numbers.\n", "\n", "To create the function $ f(x) = x^3 $ we can use `lambda` as follows" ] }, { "cell_type": "code", "execution_count": null, "id": "681294ad", "metadata": { "hide-output": false }, "outputs": [], "source": [ "from scipy.integrate import quad\n", "\n", "quad(lambda x: x**3, 0, 2)" ] }, { "cell_type": "markdown", "id": "dd61b961", "metadata": {}, "source": [ "Here the function created by `lambda` is said to be *anonymous* because it was never given a name." ] }, { "cell_type": "markdown", "id": "40fa0735", "metadata": {}, "source": [ "### Why Write Functions?\n", "\n", "User-defined functions are important for improving the clarity of your code by\n", "\n", "- separating different strands of logic \n", "- facilitating code reuse \n", "\n", "\n", "(Writing the same thing twice is [almost always a bad idea](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself))\n", "\n", "We will say more about this [later](https://python-programming.quantecon.org/writing_good_code.html)." ] }, { "cell_type": "markdown", "id": "f45ed829", "metadata": {}, "source": [ "## Applications" ] }, { "cell_type": "markdown", "id": "b45d3128", "metadata": {}, "source": [ "### Random Draws\n", "\n", "Consider again this code from the [previous lecture](https://python-programming.quantecon.org/python_by_example.html)" ] }, { "cell_type": "code", "execution_count": null, "id": "d9ade54c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "ts_length = 100\n", "ϵ_values = [] # empty list\n", "\n", "for i in range(ts_length):\n", " e = np.random.randn()\n", " ϵ_values.append(e)\n", "\n", "plt.plot(ϵ_values)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "72df3e3e", "metadata": {}, "source": [ "We will break this program into two parts:\n", "\n", "1. A user-defined function that generates a list of random variables. \n", "1. The main part of the program that \n", " 1. calls this function to get data \n", " 1. plots the data \n", "\n", "\n", "This is accomplished in the next program\n", "\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "ad0efc25", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def generate_data(n):\n", " ϵ_values = []\n", " for i in range(n):\n", " e = np.random.randn()\n", " ϵ_values.append(e)\n", " return ϵ_values\n", "\n", "data = generate_data(100)\n", "plt.plot(data)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c7369d60", "metadata": {}, "source": [ "When the interpreter gets to the expression `generate_data(100)`, it executes the function body with `n` set equal to 100.\n", "\n", "The net result is that the name `data` is *bound* to the list `ϵ_values` returned by the function." ] }, { "cell_type": "markdown", "id": "b5b83449", "metadata": {}, "source": [ "### Adding Conditions\n", "\n", "\n", "\n", "Our function `generate_data()` is rather limited.\n", "\n", "Let’s make it slightly more useful by giving it the ability to return either standard normals or uniform random variables on $ (0, 1) $ as required.\n", "\n", "This is achieved in the next piece of code.\n", "\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "08debbd6", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def generate_data(n, generator_type):\n", " ϵ_values = []\n", " for i in range(n):\n", " if generator_type == 'U':\n", " e = np.random.uniform(0, 1)\n", " else:\n", " e = np.random.randn()\n", " ϵ_values.append(e)\n", " return ϵ_values\n", "\n", "data = generate_data(100, 'U')\n", "plt.plot(data)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "4e12a8a4", "metadata": {}, "source": [ "Hopefully, the syntax of the if/else clause is self-explanatory, with indentation again delimiting the extent of the code blocks.\n", "\n", "Notes\n", "\n", "- We are passing the argument `U` as a string, which is why we write it as `'U'`. \n", "- Notice that equality is tested with the `==` syntax, not `=`. \n", " - For example, the statement `a = 10` assigns the name `a` to the value `10`. \n", " - The expression `a == 10` evaluates to either `True` or `False`, depending on the value of `a`. \n", "\n", "\n", "Now, there are several ways that we can simplify the code above.\n", "\n", "For example, we can get rid of the conditionals all together by just passing the desired generator type *as a function*.\n", "\n", "To understand this, consider the following version.\n", "\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "id": "29d60a46", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def generate_data(n, generator_type):\n", " ϵ_values = []\n", " for i in range(n):\n", " e = generator_type()\n", " ϵ_values.append(e)\n", " return ϵ_values\n", "\n", "data = generate_data(100, np.random.uniform)\n", "plt.plot(data)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "0a0f738e", "metadata": {}, "source": [ "Now, when we call the function `generate_data()`, we pass `np.random.uniform`\n", "as the second argument.\n", "\n", "This object is a *function*.\n", "\n", "When the function call `generate_data(100, np.random.uniform)` is executed, Python runs the function code block with `n` equal to 100 and the name `generator_type` “bound” to the function `np.random.uniform`.\n", "\n", "- While these lines are executed, the names `generator_type` and `np.random.uniform` are “synonyms”, and can be used in identical ways. \n", "\n", "\n", "This principle works more generally—for example, consider the following piece of code" ] }, { "cell_type": "code", "execution_count": null, "id": "d4ced894", "metadata": { "hide-output": false }, "outputs": [], "source": [ "max(7, 2, 4) # max() is a built-in Python function" ] }, { "cell_type": "code", "execution_count": null, "id": "0f2656d5", "metadata": { "hide-output": false }, "outputs": [], "source": [ "m = max\n", "m(7, 2, 4)" ] }, { "cell_type": "markdown", "id": "eadc7449", "metadata": {}, "source": [ "Here we created another name for the built-in function `max()`, which could\n", "then be used in identical ways.\n", "\n", "In the context of our program, the ability to bind new names to functions\n", "means that there is no problem *passing a function as an argument to another\n", "function*—as we did above.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "25c29504", "metadata": {}, "source": [ "## Recursive Function Calls (Advanced)\n", "\n", "\n", "\n", "This is an advanced topic that you should feel free to skip.\n", "\n", "At the same time, it’s a neat idea that you should learn it at some stage of\n", "your programming career.\n", "\n", "Basically, a recursive function is a function that calls itself.\n", "\n", "For example, consider the problem of computing $ x_t $ for some t when\n", "\n", "\n", "\n", "$$\n", "x_{t+1} = 2 x_t, \\quad x_0 = 1 \\tag{4.1}\n", "$$\n", "\n", "Obviously the answer is $ 2^t $.\n", "\n", "We can compute this easily enough with a loop" ] }, { "cell_type": "code", "execution_count": null, "id": "d98c0baf", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def x_loop(t):\n", " x = 1\n", " for i in range(t):\n", " x = 2 * x\n", " return x" ] }, { "cell_type": "markdown", "id": "f880a6b6", "metadata": {}, "source": [ "We can also use a recursive solution, as follows" ] }, { "cell_type": "code", "execution_count": null, "id": "e8ecaf1c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def x(t):\n", " if t == 0:\n", " return 1\n", " else:\n", " return 2 * x(t-1)" ] }, { "cell_type": "markdown", "id": "2b7051cf", "metadata": {}, "source": [ "What happens here is that each successive call uses it’s own *frame* in the *stack*\n", "\n", "- a frame is where the local variables of a given function call are held \n", "- stack is memory used to process function calls \n", " - a First In Last Out (FILO) queue \n", "\n", "\n", "This example is somewhat contrived, since the first (iterative) solution would usually be preferred to the recursive solution.\n", "\n", "We’ll meet less contrived applications of recursion later on.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "5f6dbd74", "metadata": {}, "source": [ "## Exercises" ] }, { "cell_type": "markdown", "id": "cfb47542", "metadata": {}, "source": [ "## Exercise 4.1\n", "\n", "Recall that $ n! $ is read as “$ n $ factorial” and defined as\n", "$ n! = n \\times (n - 1) \\times \\cdots \\times 2 \\times 1 $.\n", "\n", "We will only consider $ n $ as a positive integer here.\n", "\n", "There are functions to compute this in various modules, but let’s\n", "write our own version as an exercise.\n", "\n", "In particular, write a function `factorial` such that `factorial(n)` returns $ n! $\n", "for any positive integer $ n $." ] }, { "cell_type": "markdown", "id": "13a638f2", "metadata": {}, "source": [ "## Solution to[ Exercise 4.1](https://python-programming.quantecon.org/#func_ex1)\n", "\n", "Here’s one solution:" ] }, { "cell_type": "code", "execution_count": null, "id": "e12d1e7b", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def factorial(n):\n", " k = 1\n", " for i in range(n):\n", " k = k * (i + 1)\n", " return k\n", "\n", "factorial(4)" ] }, { "cell_type": "markdown", "id": "5c676fee", "metadata": {}, "source": [ "## Exercise 4.2\n", "\n", "The [binomial random variable](https://en.wikipedia.org/wiki/Binomial_distribution) $ Y \\sim Bin(n, p) $ represents the number of successes in $ n $ binary trials, where each trial succeeds with probability $ p $.\n", "\n", "Without any import besides `from numpy.random import uniform`, write a function\n", "`binomial_rv` such that `binomial_rv(n, p)` generates one draw of $ Y $.\n", "\n", "If $ U $ is uniform on $ (0, 1) $ and $ p \\in (0,1) $, then the expression `U < p` evaluates to `True` with probability $ p $." ] }, { "cell_type": "markdown", "id": "b2898c5c", "metadata": {}, "source": [ "## Solution to[ Exercise 4.2](https://python-programming.quantecon.org/#func_ex2)\n", "\n", "Here is one solution:" ] }, { "cell_type": "code", "execution_count": null, "id": "bc9d8cf2", "metadata": { "hide-output": false }, "outputs": [], "source": [ "from numpy.random import uniform\n", "\n", "def binomial_rv(n, p):\n", " count = 0\n", " for i in range(n):\n", " U = uniform()\n", " if U < p:\n", " count = count + 1 # Or count += 1\n", " return count\n", "\n", "binomial_rv(10, 0.5)" ] }, { "cell_type": "markdown", "id": "c10f1a99", "metadata": {}, "source": [ "## Exercise 4.3\n", "\n", "First, write a function that returns one realization of the following random device\n", "\n", "1. Flip an unbiased coin 10 times. \n", "1. If a head occurs `k` or more times consecutively within this sequence at least once, pay one dollar. \n", "1. If not, pay nothing. \n", "\n", "\n", "Second, write another function that does the same task except that the second rule of the above random device becomes\n", "\n", "- If a head occurs `k` or more times within this sequence, pay one dollar. \n", "\n", "\n", "Use no import besides `from numpy.random import uniform`." ] }, { "cell_type": "markdown", "id": "9c547cd0", "metadata": {}, "source": [ "## Solution to[ Exercise 4.3](https://python-programming.quantecon.org/#func_ex3)\n", "\n", "Here’s a function for the first random device." ] }, { "cell_type": "code", "execution_count": null, "id": "81016576", "metadata": { "hide-output": false }, "outputs": [], "source": [ "from numpy.random import uniform\n", "\n", "def draw(k): # pays if k consecutive successes in a sequence\n", "\n", " payoff = 0\n", " count = 0\n", "\n", " for i in range(10):\n", " U = uniform()\n", " count = count + 1 if U < 0.5 else 0\n", " print(count) # print counts for clarity\n", " if count == k:\n", " payoff = 1\n", "\n", " return payoff\n", "\n", "draw(3)" ] }, { "cell_type": "markdown", "id": "10caf8d3", "metadata": {}, "source": [ "Here’s another function for the second random device." ] }, { "cell_type": "code", "execution_count": null, "id": "6094bb2a", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def draw_new(k): # pays if k successes in a sequence\n", "\n", " payoff = 0\n", " count = 0\n", "\n", " for i in range(10):\n", " U = uniform()\n", " count = count + ( 1 if U < 0.5 else 0 )\n", " print(count)\n", " if count == k:\n", " payoff = 1\n", "\n", " return payoff\n", "\n", "draw_new(3)" ] }, { "cell_type": "markdown", "id": "35ea7a18", "metadata": {}, "source": [ "## Advanced Exercises\n", "\n", "In the following exercises, we will write recursive functions together." ] }, { "cell_type": "markdown", "id": "adb5309c", "metadata": {}, "source": [ "## Exercise 4.4\n", "\n", "The Fibonacci numbers are defined by\n", "\n", "\n", "\n", "$$\n", "x_{t+1} = x_t + x_{t-1}, \\quad x_0 = 0, \\; x_1 = 1 \\tag{4.2}\n", "$$\n", "\n", "The first few numbers in the sequence are $ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 $.\n", "\n", "Write a function to recursively compute the $ t $-th Fibonacci number for any $ t $." ] }, { "cell_type": "markdown", "id": "876409fb", "metadata": {}, "source": [ "## Solution to[ Exercise 4.4](https://python-programming.quantecon.org/#func_ex4)\n", "\n", "Here’s the standard solution" ] }, { "cell_type": "code", "execution_count": null, "id": "440fb646", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def x(t):\n", " if t == 0:\n", " return 0\n", " if t == 1:\n", " return 1\n", " else:\n", " return x(t-1) + x(t-2)" ] }, { "cell_type": "markdown", "id": "546d21d6", "metadata": {}, "source": [ "Let’s test it" ] }, { "cell_type": "code", "execution_count": null, "id": "f3aa3fbd", "metadata": { "hide-output": false }, "outputs": [], "source": [ "print([x(i) for i in range(10)])" ] }, { "cell_type": "markdown", "id": "42f8ea12", "metadata": {}, "source": [ "## Exercise 4.5\n", "\n", "Rewrite the function `factorial()` in from [Exercise 1](#factorial-exercise) using recursion." ] }, { "cell_type": "markdown", "id": "494bd68f", "metadata": {}, "source": [ "## Solution to[ Exercise 4.5](https://python-programming.quantecon.org/#func_ex5)\n", "\n", "Here’s the standard solution" ] }, { "cell_type": "code", "execution_count": null, "id": "b2ed22a0", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def recursion_factorial(n):\n", " if n == 1:\n", " return n\n", " else:\n", " return n * recursion_factorial(n-1)" ] }, { "cell_type": "markdown", "id": "6ff15591", "metadata": {}, "source": [ "Let’s test it" ] }, { "cell_type": "code", "execution_count": null, "id": "8c419e33", "metadata": { "hide-output": false }, "outputs": [], "source": [ "print([recursion_factorial(i) for i in range(1, 10)])" ] } ], "metadata": { "date": 1710455931.881993, "filename": "functions.md", "kernelspec": { "display_name": "Python", "language": "python3", "name": "python3" }, "title": "Functions" }, "nbformat": 4, "nbformat_minor": 5 }