{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# cs1001.py , Tel Aviv University, Spring 2020

\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Recitation 6"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Recursion recursion recursion!\n",
"\n",
"We saw two recursive functions for finding the maximal element in a list.\n",
"We discussed quicksort.\n",
"Then we wrote three recursive functions: subset sum, change and counting paths.\n",
"We've briefly discussed a combinatorial solution for the counting paths problem.\n",
"\n",
"\n",
"#### Takeaways:\n",
"- The recursive algorithms we've seen have a similar structure. Given a problem to solve recursively:\n",
" - Find the cases where the problem is solved easily (base cases, halting conditions)\n",
" - Find a method of taking a big problem and reducing it to (one ore more) smaller problems\n",
" - Find how to relate the solution to the smaller problems into the big problem\n",
"- The recursion tree helps in bounding the recursion depth and time complexity. Each tree node represents a call to the recursive function. We write the relevant size of the input inside the tree node, and for each node we also keep the total amount of work done for this input, not including the time spent on the recursive call.\n",
"- The recursion depth of a recursive function is the maximal number of open recursive calls at a given moment. Note that python has a limit on this value. Analyzing the recursion depth is analogous to computing the length of the longest root-leaf path in the recursion tree.\n",
"- The time complexity of a recursive function is the total amount of work performed by all the tree nodes.\n",
"- The space complexity of a recursive function is the total amount of space used by the \"heaviest\" root-leaf path in the tree."
]
},
{
"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": [
"## Max1 \n",
"The maximum is the maximal value between lst[0] and the result of recursively finding the max in lst[1:].\n",
"\n",
"Let $n$ denote the size of lst.\n",
"\n",
"Recursion depth: $O(n)$\n",
"\n",
"Time complexity: $O(n^2)$"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def max1(L): \n",
" if len(L) == 1:\n",
" return L[0]\n",
" \n",
" without_first = max1(L[1:])\n",
" \n",
" if without_first > L[0]:\n",
" return without_first\n",
" else:\n",
" return L[0]\n",
" \n",
" \n",
" \n",
" \n",
" \n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Max2\n",
"The maximum is the maximal value between the result of recursively finding the max in lst[:n//2] and the result of recursively finding the max in lst[n//2:], where $n$ denotes the size of lst.\n",
"\n",
"Recursion depth: $O(\\log{n})$\n",
"\n",
"Time complexity: $O(n\\log{n})$"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def max2(L): \n",
" if len(L) == 1:\n",
" return L[0]\n",
" \n",
" l = max2(L[:len(L) // 2])\n",
" r = max2(L[len(L) // 2:])\n",
" \n",
" if l > r:\n",
" return l\n",
" else:\n",
" return r"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Now without slicing\n",
"Since slicing is a costly action we can do things better. Instead of slicing the list each time we will maintain indices for the \"active\" part of the list (like we did for binary search) and simply recurse after updating the indices according to the same logic.\n",
"\n",
"We also add envelope functions for a more user-friendly code.\n",
"\n",
"How does time/depth change for each function? \n",
"The depth is clearly unaffected. Time, however, is much better. \n",
"\n",
"Since we only do $O(1)$ work in the function, the runtime is analogous to computing the size of the tree which is $O(n)$ in both cases."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def max11(L,left,right): \n",
" if left == right:\n",
" return L[left]\n",
" \n",
" without_left = max11(L, left + 1, right)\n",
" \n",
" if without_left > L[left]:\n",
" return without_left\n",
" else:\n",
" return L[left]\n",
"\n",
" \n",
" \n",
"def max22(L, left, right): \n",
" if left == right:\n",
" return L[left]\n",
" \n",
" mid = (left + right) // 2\n",
" l = max22(L, left, mid)\n",
" r = max22(L, mid + 1, right)\n",
" \n",
" if l > r:\n",
" return l\n",
" else:\n",
" return r\n",
"\n",
"def max1_noslice(L):\n",
" return max11(L, 0, len(L) - 1)\n",
"\n",
"def max2_noslice(L):\n",
" return max22(L, 0, len(L) - 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### comparison in running times"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"max1\n",
"n= 500 : 0.015625\n",
"n= 1000 : 0.109375\n",
"n= 2000 : 0.484375\n",
"max2\n",
"n= 500 : 0.015625\n",
"n= 1000 : 0.015625\n",
"n= 2000 : 0.046875\n"
]
}
],
"source": [
"import time\n",
"import random\n",
"import sys\n",
"sys.setrecursionlimit(3000)\n",
"\n",
"\n",
"for f in [max1, max2]:\n",
" print(f.__name__)\n",
" for n in [500, 1000, 2000]:\n",
" L = [i for i in range(n)]\n",
" random.shuffle(L)\n",
" tic = time.process_time()\n",
" for x in range(10):\n",
" m = f(L)\n",
" toc = time.process_time()\n",
" print(\"n=\", n, \": \",toc - tic)\n",
" \n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Quick Sort"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### The logic\n",
"Quicksort has a very simple recursive logic:\n",
"* A list of size 1 is trivially sorted\n",
"* Otherwise, pick some element $x \\in L$ and let:\n",
" * $less = \\{y \\in L : y < x\\}$\n",
" * $eq = \\{y \\in L : y = x\\}$ (note: $eq$ is trivially sorted)\n",
" * $more = \\{y \\in L : y > x \\}$\n",
"* Recursively sort $less, more$ and return $less+eq+more$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Random:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import random\n",
"def quicksort(lst):\n",
" \"\"\" quick sort of lst \"\"\"\n",
" if len(lst) <= 1: \n",
" return lst\n",
" else:\n",
" pivot = random.choice(lst) # select a random element from list\n",
" smaller = [elem for elem in lst if elem < pivot] \n",
" equal = [elem for elem in lst if elem == pivot] \n",
" greater = [elem for elem in lst if elem > pivot]\n",
" return quicksort(smaller) + equal + quicksort(greater) #two recursive calls"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Deterministic:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"def det_quicksort(lst):\n",
" \"\"\" sort using deterministic pivot selection \"\"\"\n",
" if len(lst) <= 1: \n",
" return lst\n",
" else:\n",
" pivot = lst[0] # select first element from list\n",
" smaller = [elem for elem in lst if elem < pivot] \n",
" equal = [elem for elem in lst if elem == pivot] \n",
" greater = [elem for elem in lst if elem > pivot]\n",
" return det_quicksort(smaller) + equal + det_quicksort(greater) #two recursive calls"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Analysis\n",
"\n",
"The worst case and best case analyses were discussed in class. It is interesting to note that:\n",
"* The worst case for quicksort has a recursion tree similar to that of $max1$, i.e. - in each recursive call we reduce the input size by $1$ giving a running time of $O(n^2)$\n",
"* The base case for quicksort has a recursion tree similar to that of $max2$, i.e. - each instance of the function on input of size $n$ recurses twice on inputs of size roughly $n/2$, giving a running time of $O(n \\cdot \\log n)$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Subset sum\n",
"\n",
"The subset sum problem is described as follows: given a list of integers $L$ and a value $s \\in \\mathbb{Z}$, is there a subset $T \\subseteq L$ such that: $$\\sum_{x \\in T} x = s$$ If such an $T$ exists we return True, otherwise False.\n",
"\n",
"Examples: \n",
"* For $L = [4, -7, 12, 5, 1], s = 6$ we will say yes, as $-7+1+12 = 6$ (also, $5+1=6$).\n",
"* For $L = [1, 2, 4, 8, 16], s= 32$ we will say no as all elements are positive and $\\sum_{x \\in L} = 31$\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The recursive structure\n",
"\n",
"The base cases are pretty straight-forward:\n",
"* If we need to reach $s = 0$ then we have succeeded (i.e. - return True)\n",
"* If we need to reach some $s \\neq 0$ but $L = []$ then we have failed (i.e. - return False)\n",
"\n",
"What about the recursive call? Well, if $s \\neq 0, L \\neq []$ then the following holds:\n",
"* Either there's a way of \"reaching\" $s$ by taking the first element in $L$\n",
"* Or there's a way of \"reaching\" $s$ by **not** taking the first element in $L$\n",
"* If both of the above fail, there is no way of \"reaching\" $s$ using $L$\n",
"\n",
"So what do we do? We recursively check if either $L[1:], s - L[0]$ or $L[1:], s$ can be solved, and we only return False if both fail. Let's code:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"def subset_sum(L, s):\n",
" if s == 0:\n",
" return True\n",
" if L == []:\n",
" return False\n",
" \n",
" with_first = subset_sum(L[1:], s - L[0])\n",
" without_first = subset_sum(L[1:], s)\n",
" return with_first or without_first\n",
"\n",
"# Sanity checks\n",
"L1 = [4, -7, 12, 5, 1]\n",
"L2 = [1, 2, 4, 8, 16]\n",
"s1 = 6\n",
"s2 = 32\n",
"\n",
"print(subset_sum(L1, s1))\n",
"print(subset_sum(L2, s2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Analysis\n",
"\n",
"What is the running time of the code in relation to the size of the list $|L| = n$?\n",
"\n",
"We can implement a solution that does not make use of slicing. Let's analyze it:\n",
"\n",
"The recurrence relation is clearly $T(n) = 2 \\cdot T(n-1) + O(1)$, which yields $T(n) = 2^n$. \n",
"\n",
"In class we've seen how to transform recursive algorithms which run in exponential time into iterative algorithms that run in linear time (i.e. - Fibonacci, factorial). \n",
"\n",
"Can you think of a better solution? One that works in time $O(n^2)$? How about $O(n^{100})$?\n",
"\n",
"Incredibly, there is a wide held belief that this problem yields no algorithm which runs in time $\\mathrm{poly}(n)$. More on that later (much later, say, next year in computational models)..."
]
},
{
"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": null,
"metadata": {},
"outputs": [],
"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": [
"## Recursion tree for change(5, [1, 2, 3])\n",
"\n",
"![Recursion Tree for change(5, [1,2,3])](rec6_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 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.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Subset sum vs. Change\n",
"\n",
"It is interesting to note that while the two problem 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": null,
"metadata": {},
"outputs": [],
"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",
"We will show that this solution is intractable. That is, the time complexity is at least exponential in the input size.\n",
"\n",
"Let's look at a simple case where $d = |L|= 2$ and $L = [n, n]$.\n",
"Consider the recursion tree for this input. In the first $n-1$ levels of the tree each node has exactly 2 children (why?).\n",
"The overall number of nodes in the first $n$ levels of the tree is $\\Sigma_{i=0}^{n-1}{2^i} = 2^n - 1$.\n",
"Note that there are many more nodes in the tree that we did not count.\n",
"\n",
"Suppose that the amount of work for each node is $O(1)$, then the overall time complexity of the function is at least $\\text{num_of_nodes} \\times \\text{work_per_node}$. That is the time complexity is at least exponential in $n$.\n",
"\n",
"Now, let's look at a slight generalization, 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",
"As before, the number of nodes in the first $n$ levels of the tree is $\\Sigma_{i=0}^{n-1}{d^i} \\approx d^n = 2^{\\log{d^n}} = 2^{n\\log{d}}$.\n",
"Therefore, the time complexity is at least exponential in both $n, \\log{d}$.\n",
"\n",
"\n",
"Another way to bound (from below) the number of nodes in the tree is to count the number of leaves in the tree. Since at each leaf we return 1, the number of leaves is actually the number $cnt$ of \"legal paths\" that we count.\n",
"\n",
"It can be shown (combinatorically) that $cnt$ is at least exponential in $d,n$."
]
},
{
"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
}