Skip to content

Monday 10/2

For Loop Reminder

See the notes from last Wednesday for some examples of for loop patterns.

Some other patterns to be aware of:

Accumulator - We often need to somehow combine all of the elements in a collection:

nums = [1, 7, 11]

total = 0  # Create a location for the accumulated result.
for x in nums:
    total += x

Sequential Search - Sometimes we need to iterate through a collection until we find something, or determine that it isn't here.

def contains_negative(numbers):
    """Return true if the provided list contains a negative number.

    Args:
        numbers (list): A list of numbers

    Returns:
        bool: True if there is a negative number, False otherwise.
    """
    for x in numbers:
        if x < 0:
            return True
        # We don't want an else here! We can't know whether
        # to return False until we've looked at all numbers

    return False  # This happens after the loop finishes.
                  # If we never returned, there are no negative
                  # numbers.

Accessing Neighbors - Sometimes we need to access an element as well as it's neighbor in the collection. In this case, we need to use an indexed for loop:

def all_pairs(sentence):
    """Return a set containing all neighboring pairs of letters.

    For example:
    >>> all_pairs("abcaaaaab")
    {'ab', 'aa', 'bc', 'ca'}

    Args:
        sentence (string): Any string

    Returns:
        set: A set containing all unique pairs of neighboring letters.
    """
    all_pairs = set()
    for i in range(len(sentence) - 1):  # Stop one index *before* the end.
        letter = sentence[i]
        next_letter = sentence[i + 1]
        all_pairs.add(letter + next_letter)
    return all_pairs

Loop Activities

Please work with a partner on the activities below. For the coding bat exercises, you should each select a different problem. When you finish a problem, explain your solution to your partner.

Tallest

Complete the following function so that the behavior matches the docstring. There is nothing to submit, just show your instructor when you have it working.

def get_tallest(heights):
    """Return the name of the tallest person.

    Example:

    >>> get_tallest({"Sharon": 6.2, "Ali": 5.9})
    Sharon

    Args:
        heights (dict): a dictionary mapping from names (strings) to
            height in feet (floats).

    Returns:
        string: the name of the tallest person.
    """

CodingBat Problems

List-2 Problems

Do NOT use the built-in functions like min(), max(), or sum() on these problems. They should all be solved using for-loops.

  • Easier: count_evens, has22
  • Medium: big_diff, sum13
  • Harder: centered_average, sum67

String-2 Problems

  • Easier: double_char, count_hi
  • Medium: count_code, cat_dog
  • Harder: xyz_there, end_other