Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Wrapping Up
Дальше: Chapter 12: Dynamic Programming

Exercises

The following exercises provide you with the opportunity to practice with recursion. The solutions to these exercises are found in the section .

  1. Use recursion to write a function that accepts an array of strings and returns the total number of characters across all the strings. For example, if the input array is ["ab", "c", "def", "ghij"], the output should be 10 since there are ten characters in total.

  2. Use recursion to write a function that accepts an array of numbers and returns a new array containing just the even numbers.

  3. A particular numerical sequence is known as triangular numbers. The pattern begins as 1, 3, 6, 10, 15, 21, and continues onward. To calculate the next number in the sequence, we add the previous number from the sequence plus N, where N corresponds to the place in the sequence where the number lies. For example, the seventh number in the sequence is 28, since it’s the seventh number in the pattern, so we add the number 7 plus 21 (the previous number in the sequence). Write a function that accepts a number for N and returns the correct number from the series; that is, if the function was passed the number 7, the function would return 28.

  4. Use recursion to write a function that accepts a string and returns the first index that contains the character “x”. For example, the string, "abcdefghijklmnopqrstuvwxyz" has an “x” at index 23. To keep things simple, assume the string definitely has at least one “x”.

  5. This problem is known as the unique paths problem: Let’s say you have a grid of rows and columns. Write a function that accepts a number of rows and a number of columns and calculates the number of possible “shortest” paths from the upper-leftmost square to the lower-rightmost square.

    For example, here’s what the grid looks like with three rows and seven columns. You want to get from the S (Start) to the F (Finish).

    /books/45079/OEBPS/learning_to_write_in_recursive/unique_paths_setup.png

    By “shortest” path, I mean that at every step, either you’re moving one step to the right:

    /books/45079/OEBPS/learning_to_write_in_recursive/unique_paths_move_right.png

    Or you’re moving one step downward:

    /books/45079/OEBPS/learning_to_write_in_recursive/unique_paths_move_down.png

    Again, your function should calculate the number of shortest paths.

Назад: Wrapping Up
Дальше: Chapter 12: Dynamic Programming