{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

cs1001.py , Tel Aviv University, Spring 2019

\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###### Recitation 7" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We continued discussing recursion.\n", "We also discussed memoization and demonstrated it.\n", "\n", "\n", "#### Takeaways:\n", "- Memoization is mainly technical. Remember the main steps of defining an envelope function, deciding what keys you use to describe the input, \n", "and finally changing your recursive implementation so that it will search for the key in the dictionary before making the recursive calls, and save the key:value pair after obtaining the value for a certain input. \n", "- The keys of the dictionary should be chosen to represent the current input to the function in a one-to-one fashion.\n", "- When analyzing the time complexity of a recursive function with memoization, consider the recursion tree and remember that a node that has already been computed will not have a subtree." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Code for printing several outputs in one cell (not part of the recitation):" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from IPython.core.interactiveshell import InteractiveShell\n", "InteractiveShell.ast_node_interactivity = \"all\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Change problem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A bus driver needs to give an exact change and she has coins of limited types. She has infinite coins of each type.\n", "Given the amount of change ($amount$) and the coin types (the list $coins$), how many ways are there? \n", "\n", "* There are two base cases:\n", " * If $amount == 0$ then there is one way of returning change - not giving any coins (return 1)\n", " * If $amount < 0$ or $coins = []$ (and $amount > 0$), there are no ways of return change (return 0)\n", "* Otherwise, the logic is very similar to that of the subset sum problem. We pick one coin from the list (say, the last one this time), and we again have two options:\n", " * Either we use the last coin and then check how many ways we have of returning the rest of the amount\n", " * We don't use the last coin at all and check how many ways we have of returning the amount\n", "* Summing the two options above gives the total number of ways to return the change\n", "\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def change(amount, coins):\n", " if amount == 0:\n", " return 1\n", " elif amount < 0 or coins == []:\n", " return 0\n", " return change(amount, coins[:-1]) +\\\n", " change(amount - coins[-1], coins)\n", " \n", "change(5, [1,2,3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Why is it counting unique solutions? For example, why is [2,2,1] counted once and not [1,2,2]?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Recursion tree\n", "\n", "![Recursion Tree for change(5, [1,2,3])](rec5_change_tree.png \"Title\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Analysis\n", "\n", "Consider the case where $amount = n^2, coins = [1,2,\\ldots, n]$. When we call $change(amount, coins)$ the first level of the recursion calls $change([1,\\ldots, n-1], n^2)$ and $change([1,\\ldots, n], n^2 - n)$. This means that the list size in the recusrive calls is at least $n-1$ and $amount \\geq n^2 -n$.\n", "\n", "One can show (using induction) that in the first $k \\leq n$ levels of recursion the list size is at least $n - k$ and $amount \\geq n^2-n k$, thus there are two recursive calls at each of these layers. \n", "\n", "This gives a running time of at least $2^n$ by the same argument as that we applied in the subset sum problem." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Subset sum vs. Change\n", "\n", "It is interesting to note that while the two problems share some similarities, one major difference is that in the subset sum problem we are asking whether a **solution exists** while in the change problem we are trying to **count** the number of valid solutions to a problem.\n", "\n", "This is a recurring theme in CS that we will encounter many times in the future." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Counting paths\n", "\n", "Question 2(a) from the 2015 fall semester exam (Moed B).\n", "\n", "Given a list $L$ of non-negative integers with $len(L) = d$ we consider $L$ as a point in a $d$-dimensional space.\n", "\n", "For example: $L = [0, 0, 0]$ represents the origin in a $3$-dimensional space.\n", "\n", "Our goal is to find how many ways we have of getting from $[0, \\ldots, 0]$ to $L$ by advancing **only forward**.\n", "\n", "For example, if $L=[1, 2]$ then we have three such paths:\n", "* $[0,0] \\to [1, 0] \\to [1, 1] \\to [1,2]$\n", "* $[0,0] \\to [0, 1] \\to [1, 1] \\to [1,2]$\n", "* $[0,0] \\to [0, 1] \\to [0, 2] \\to [1,2]$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again, we first think of the base case, and then reduce big problems to smaller ones.\n", "\n", "* If $L$ has only zeros then there is a single possible path - not taking any steps.\n", "* Otherwise, we have the following relation, let $L = [a_1, \\ldots, a_n]$, then: $$paths([a_1, \\ldots, a_n]) = \\sum_{i : a_i > 0}paths([a_1,\\ldots, a_i - 1, \\ldots, a_n])$$\n", "\n", "This gives rise to a simple recursive algorithm:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "27720\n" ] } ], "source": [ "def cnt_paths(L):\n", " if all_zeros(L):\n", " return 1\n", " \n", " result = 0\n", " for i in range(len(L)):\n", " if L[i] != 0:\n", " L[i] -= 1\n", " result += cnt_paths(L)\n", " L[i] += 1\n", " return result\n", "\n", "def all_zeros(L):\n", " for i in L:\n", " if i != 0:\n", " return False\n", " return True\n", "\n", "\n", "print(cnt_paths([3,4,5]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Analysis\n", "\n", "Note that the leaves in the tree are exactly the \"legal paths\" which we count.\n", "\n", "Let $cnt$ be the returned value of $cnt\\_paths(L)$. Since we increment $cnt$ by $1$ for each legal path, this means that the running time is **at least $cnt$**.\n", "\n", "Using the following combinatorial analysis, which is **for reference only**, we show that\n", "$cnt$ is exponential in $d,n$, implying that the running time of $cnt\\_paths(L)$ is at least exponential in $d,n$.\n", "Can we do better than the recursive solution in terms of running time? ...yes!\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Combinatorial solution (for reference only)\n", "\n", "Let's take a simple case where $L = [n, n, \\ldots, n]$ and $|L| = d$. I.e. - we are in a $d$-dimensional space and we want to get to $[n, \\ldots, n]$.\n", "\n", "Can you think of a combinatorial solution for cnt_paths? Let's take the case above where $L = [n, n, \\ldots, n]$ and $|L| = d$. \n", "\n", "In each step we subtract $1$ from one of the $d$ coordinates (which is currently positive) and in exactly $nd$ steps we need to get to the all-zero vector.\n", "\n", "Think about the first coordinate - there are precisely $n$ steps along our path where we change this coordinate, thus we have $\\binom{nd}{n}$ options to choose where the moves for the first coordinate are located.\n", "\n", "What about the second coordainte? Well now we are left with $nd - n = n(d-1)$ places out of which we again pick $n$ places to advance the second coordinate. By indcution, we get: $$cnt = \\prod_{i=1}^d \\tbinom{n(d-i+1)}{n} = \\prod_{i=1}^d \\tbinom{ni}{n} $$\n", "\n", "How long does it take to compute this number? We need to multiply $d$ elements, and for each of those we need to compute factorials and divide numbers in the range of $1,\\ldots,n$. This is clearly done in time polynomial in $d,n$.\n", "\n", "And how big is $cnt$ exactly? Recall that $cnt$ is a bound on the running time of cnt_paths. \n", "\n", "We now claim that $cnt = exp(n,d)$. To see this, we write it explicitly:\n", "\n", "$$cnt = \\tbinom{n}{n}\\cdot \\tbinom{2n}{n} \\cdots \\tbinom{dn}{n} = \\frac{n!}{(n-n)! n!} \\cdot \\frac{(2n)!}{(2n-n)! n!} \\cdot \\frac{(3n)!}{(3n-n)! n!}\\cdots \\frac{(nd)!}{(nd-n)! n!} $$\n", "\n", "This product has a telescopic property - thus we can cancel out elements and get: \n", "\n", "$$cnt = \\frac{(nd)!}{(n!)^d} = \\frac{1\\cdot 2 \\cdot 3 \\cdots \\cdot nd}{(1 \\cdot 2 \\cdots n) \\cdots(1 \\cdot 2 \\cdots n)} $$\n", "\n", "Break this product into two terms:\n", "\n", "$$cnt = \\frac{1 \\cdots 2n}{n! \\cdot n!} \\cdot \\frac{(2n + 1) \\cdots nd }{(n!)^{d - 2}}$$\n", "\n", "The first multiplicand is clearly larger than $1$, as for the second, each term in the numerator is **at least** $2n$ and each term in the denominator is **at most** $n$ thus clearly: $$cnt \\gg \\frac{2n \\cdot 2n \\cdots 2n}{n \\cdot n \\cdot n} = 2^{dn - 2n} = exp(n,d)$$\n", "\n", "Conclusion? Using the combinatorial computation we reduce a running time which is exponential in $n,d$ into a running time polynomial in $n,d$.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Memoization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Binom \n", "The number of sets of size $k$ selected from a set of $n$ elements (with no repetitions)\n", "Recursive formula (Pascal):\n", "$\\binom{n}{k} = \\binom{n-1}{k} + \\binom{n-1}{k-1}$\n", "where the stopping criterion is $\\binom{n}{0} = \\binom{n}{n} = 1$\n", "\n", "The time complexity of binom is exponential in $n$ (worst case behaviour is when $k=\\frac{n}{2}$)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def binom(n,k):\n", " if n < 0 or k < 0 or n < k:\n", " return 0\n", " elif (k==0 or n==k):\n", " return 1\n", " return binom(n-1,k-1) + binom(n-1,k)\n", "\n", "binom(4,2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Printing the recursive calls using tracing:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ">>(4,2)\n", ">>>>(3,2)\n", ">>>>>>(2,2)\n", "<<<<<<(2,2)\n", ">>>>>>(2,1)\n", ">>>>>>>>(1,1)\n", "<<<<<<<<(1,1)\n", ">>>>>>>>(1,0)\n", "<<<<<<<<(1,0)\n", "<<<<<<(2,1)\n", "<<<<(3,2)\n", ">>>>(3,1)\n", ">>>>>>(2,1)\n", ">>>>>>>>(1,1)\n", "<<<<<<<<(1,1)\n", ">>>>>>>>(1,0)\n", "<<<<<<<<(1,0)\n", "<<<<<<(2,1)\n", ">>>>>>(2,0)\n", "<<<<<<(2,0)\n", "<<<<(3,1)\n", "<<(4,2)\n" ] }, { "data": { "text/plain": [ "6" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def binom_trace(n,k):\n", " result = binom_trace(n,k)\n", " return result\n", "\n", "def binom_trace(n,k,indent=1):\n", " #indent = how much to indent the printouts\n", " if (k<0 or n<0 or n>\"*indent + \"({},{})\".format(n,k))\n", " print(\"<<\"*indent + \"({},{})\".format(n,k))\n", " return 1\n", " print(\">>\"*indent + \"({},{})\".format(n,k))\n", " indent+=1\n", " val = binom_trace(n-1,k,indent) + binom_trace(n-1,k-1,indent)\n", " indent-=1\n", " print(\"<<\"*indent + \"({},{})\".format(n,k))\n", " return val\n", "\n", "binom_trace(4,2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now with memoization:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" }, { "data": { "text/plain": [ "126410606437752" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def binom_fast(n,k):\n", " d = {}\n", " return binom_mem(n,k,d)\n", "\n", "def binom_mem(n,k,mem):\n", " if n < 0 or k < 0 or n < k:\n", " return 0\n", " elif (k==0 or n==k):\n", " return 1\n", " if (n,k) not in mem:\n", " mem[(n,k)] = binom_mem(n-1,k, mem) + \\\n", " binom_mem(n-1,k-1, mem)\n", " return mem[(n,k)]\n", "\n", "binom_fast(4,2)\n", "binom_fast(50,25)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Printing the recursive calls, with memoization:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ">>(4,2)\n", ">>>>(3,2)\n", ">>>>>>(2,2)\n", "<<<<<<(2,2)\n", ">>>>>>(2,1)\n", ">>>>>>>>(1,1)\n", "<<<<<<<<(1,1)\n", ">>>>>>>>(1,0)\n", "<<<<<<<<(1,0)\n", "<<<<<<(2,1)\n", "<<<<(3,2)\n", ">>>>(3,1)\n", ">>>>>>(2,1)\n", "<<<<<<(2,1)\n", ">>>>>>(2,0)\n", "<<<<<<(2,0)\n", "<<<<(3,1)\n", "<<(4,2)\n" ] }, { "data": { "text/plain": [ "6" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def binom_fast_trace(n,k):\n", " mem = dict()\n", " result = binom_mem_trace(n,k,mem)\n", " return result\n", "\n", "def binom_mem_trace(n,k,mem,indent=1):\n", " #indent = how much to indent the printouts\n", " if (k<0 or n<0 or n>\"*indent + \"({},{})\".format(n,k))\n", " print(\"<<\"*indent + \"({},{})\".format(n,k))\n", " return 1\n", " print(\">>\"*indent + \"({},{})\".format(n,k))\n", " indent+=1\n", " if (n,k) not in mem:\n", " mem[(n,k)] = binom_mem_trace(n-1,k,mem,indent) + binom_mem_trace(n-1,k-1,mem,indent)\n", " indent-=1\n", " print(\"<<\"*indent + \"({},{})\".format(n,k))\n", " return mem[(n,k)]\n", "\n", "\n", "binom_fast_trace(4,2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Analysis of binom_fast(n,k):\n", "\n", "To analyze the time complexity of the function, we will construct an $ (n+1) \\times (k+1)$ table, where the cell in position $(i,j)$ will denote a call to compute $\\binom{i}{j}$.\n", "\n", "In this method, the running time can be computed by $$\\text{number of visited cells} \\times \\text{number of visits per cell} \\times \\text{time per cell (without recursive calls)}$$\n", "\n", "Consider a cell in position $(i,j)$. By our recursive formula, this cell will be called exactly in the cases where we need to compute either $(i + 1, j)$ or $(i + 1, j + 1)$.\n", "\n", "Now, assume $(i+1, j)$ was the first cell to call $(i,j)$, then:\n", "* No call to $(i+1, j+1)$ will be initiated before the call to $(i +1,j)$ is completed (this is obvious by the structure of the formula)\n", "* Once the call to $(i +1,j)$ is completed, $(i, j)$ will be in the dictionary\n", "* At this point, the call to $(i + 1, j +1 )$ will not need to compute $(i,j)$ from scratch as it is already in the dictionary\n", "* Once $(i +1, j)$ and $(i+1,j+1)$ are both computed, the code will never call $(i,j)$ again, since they are both in the dictionary\n", "\n", "It follows that each cell will be accessed at most twice, and thus the running time is clearly $O(nk)$. In the diagram below we see that we can even give a more precise running time based on the fact that many cells in the table are base cases.\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Change problem - now with memoization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A bus driver needs to give an exact change and she has coins of limited types. She has infinite coins of each type.\n", "Given the amount of change ($amount$) and the coin types (the list $coins$), how many ways are there? \n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def change(amount, coins):\n", " if amount == 0:\n", " return 1\n", " elif amount < 0 or coins == []:\n", " return 0\n", " return change(amount, coins[:-1]) +\\\n", " change(amount - coins[-1], coins)\n", " \n", "change(5, [1,2,3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now with memoization:\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "21084" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def change_fast(amount, coins):\n", " d = {}\n", " return change_mem(amount, coins, d)\n", "\n", "def change_mem(amount, coins, d):\n", " if amount == 0:\n", " return 1\n", " elif amount < 0 or coins == []:\n", " return 0\n", " #if (amount, tuple(coins)) not in d:\n", " if (amount, len(coins)) not in d:\n", " #d[(amount, tuple(coins))] = \\\n", " d[(amount, len(coins))] = \\\n", " change_mem(amount, coins[:-1], d) +\\\n", " change_mem(amount - coins[-1], coins, d)\n", " #return d[(amount, tuple(coins))]\n", " return d[(amount, len(coins))]\n", "\n", "change_fast(500, [1,3,2])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.7.2" } }, "nbformat": 4, "nbformat_minor": 1 }