These are the solutions to the exercises found in the section, Exercises . The solutions provided here are in Python, but you can find the solutions in JavaScript and Ruby in the code download. [10]
-
The base case is if low > high —that is, we want to stop the recursion once low has exceeded high . Otherwise, we’d end up printing numbers even greater than the high number, and onto infinity.
-
We’d have infinite recursion! factorial(10) calls factorial(8) , which calls factorial(6) , which calls factorial(4) , which calls factorial(2) , which calls factorial(0) . Since our base case is if n == 1 , we never end up with n ever being 1, so the recursion continues. factorial(0) calls factorial(-2) , and so on.
-
Let’s say low is 1 and high is 10. When we call sum(1, 10) , that in turn returns 10 + sum(1, 9) . That is, we return the sum of 10 plus whatever the sum of 1 through 9 is. sum(1, 9) ends up calling sum(1, 8) , which in turn calls sum(1, 7) , and so on.
We want the last call to be sum(1, 1) , in which we simply want to return the number 1 . This becomes our base case:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>sum</strong> (low, high):</td></tr><tr><td> <span> </span></td><td> <em># Base case:</em> </td></tr><tr><td> <span> </span></td><td> <strong>if</strong> high == <em>low:</em> </td></tr><tr><td> <span> </span></td><td> <em></em> <strong>return</strong> low</td></tr><tr><td> <span> </span></td><td></td></tr><tr><td> <span> </span></td><td> <strong>return</strong> high + sum(low, high - 1)</td></tr></tbody></table>
-
This approach is similar to the file directory example from the text:
<table><tbody><tr><td> <span> </span></td><td> <strong>def</strong> <strong>print_all_items</strong> (array):</td></tr><tr><td> <span> </span></td><td> <strong>for</strong> value <strong>in</strong> <em>array:</em> </td></tr><tr><td> <span> </span></td><td> <em></em> <em># if the current item is a "list", i.e. array:</em> </td></tr><tr><td> <span> </span></td><td> <strong>if</strong> isinstance(value, list):</td></tr><tr><td> <span> </span></td><td>print_all_items(value)</td></tr><tr><td> <span> </span></td><td> <em>else:</em> </td></tr><tr><td> <span> </span></td><td> <em></em>print(value)</td></tr></tbody></table>
We iterate over each item within the outer array. If the value is itself another array, we recursively call the function on that subarray. Otherwise, it’s the base case where we simply print the value to the screen.