The following exercises provide you with the opportunity to practice with dynamic programming. The solutions to these exercises are found in the section, ​ Chapter 12 ​ .

  1. The following function accepts an array of numbers and returns the sum, as long as a particular number doesn’t bring the sum above 100. If adding a particular number will make the sum higher than 100, that number is ignored. However, this function makes unnecessary recursive calls. Fix the code to eliminate the unnecessary recursion:

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>def</strong> ​ ​ <strong>add_until_100</strong> ​(array)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ 0 ​ <strong>if</strong> ​ array.​ <strong>length</strong> ​ == 0</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>if</strong> ​ array[0] + add_until_100(array[1, array.​ <strong>length</strong> ​ - 1]) &gt; 100</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ add_until_100(array[1, array.​ <strong>length</strong> ​ - 1])</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>else</strong> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ array[0] + add_until_100(array[1, array.​ <strong>length</strong> ​ - 1])</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>end</strong> ​</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>end</strong> ​</td></tr></tbody></table>

  2. The following function uses recursion to calculate the Nth number from a mathematical sequence known as the “Golomb sequence.” It’s terribly inefficient, though! Use memoization to optimize it. (You don’t have to actually understand how the Golomb sequence works to do this exercise.)

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>def</strong> ​ ​ <strong>golomb</strong> ​(n)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ 1 ​ <strong>if</strong> ​ n == 1</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ 1 + golomb(n - golomb(golomb(n - 1)));</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>end</strong> ​</td></tr></tbody></table>

  3. Here is a solution to the “Unique Paths” problem from an exercise in the previous chapter. Use memoization to improve its efficiency:

    <table><tbody><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>def</strong> ​ ​ <strong>unique_paths</strong> ​(rows, columns)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ 1 ​ <strong>if</strong> ​ rows == 1 || columns == 1</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>return</strong> ​ unique_paths(rows - 1, columns) + unique_paths(rows, columns - 1)</td></tr><tr><td>​ <span>&nbsp;</span></td><td>​ <strong>end</strong> ​</td></tr></tbody></table>

Copyright © 2020, The Pragmatic Bookshelf.