"Recursion Was So Last Year"

Actually, that’s not true. Recursion is a wonderful and powerful concept that you will put to a lot of use. However, for many simpler tasks a for (or while) loop provides a more direct way to accomplish the task.

Doing Stuff Over and Over

Let’s look into summing the elements of a list. Long ago we did this using recursion. Today we’ll do it more directly using a for loop.

def sum_numbers(numbers):
    # Initialize a variable to sum numbers into
    sum = 0
    # Walk through all the items in the list...
    for number in numbers:
        # Accumulate each number into sum
        sum = sum + number
    # Return the sum to the user
    return sum

Now we can use this function from our code.

# ...Rest of function elided...
even = range(2, 20, 2)
even_sum = sum_numbers(even)
print even_sum

Not to bad, eh?

Challenges to Work Through

Note that none of these functions should use recursion.

  • Write a function to find the maximum element in a list. You may not use the max() function that is already defined in Python. The function should be called max_numbers, take is input a list of numbers, and return the maximum element in the list.

  • Write a function to print each item in a list. The function should be called print_list, take as intput a list, and does not need to return anything.

  • Write a function to count the number of times that a letter appears in a string. The function should be called count_char, take is intput a character and a string, and return the number of times that the character is within the string. Note that a string is simply a list of characters, so you can iterate through the characters in a string using for letter in string. Example calls to this function:

churchill = "A lie gets halfway around the world before the truth has a chance to get its pants on."
print count_char('x', churchill) # Expecting 0
print count_char('w', churchill) # Expecting 2
print count_char('a', churchill) # Expecting 7 (not 8)
  • Write a function to replace each instance of one character with another within a string. The function should be called replace_char, take as input a character to look for / a character to replace it with / a string, and return the modified string.

churchill = "A lie gets halfway around the world before the truth has a chance to get its pants on."
print count_char('w', 'x', churchill) # Expecting "A lie gets halfxay around the xorld before the truth has a chance to get its pants on."
  • BONUS Rewrite the count_char function to ignore the case of letters. The lower function included in the string class may be of help with this.