{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Common Loop Patterns\n", "\n", "When we use loops, there are often a set of common patterns that we use. For example, we may go through all the elements of a list and find the items with the highest value. Or do something with every element of the list, and store the result in another.\n", "\n", "Below, we will discuss a few of these common patterns. Most of these patterns have the following structure:\n", "\n", "* Initialize one or more variables before the loop starts\n", "* Perform some computation on each item in the loop body, possibly changing the variables in the body of the loop\n", "* Look at the resulting variables when the loop completes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summing Elements" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's say now that we want to sum all the elements in a list. \n", "\n", "Here is an example list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = [40, 27, 50, 15, 32, 16, 31, 38, 45, 33]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could of course use the `sum()` function," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sum(numbers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " but let's write this as a loop, to understand the pattern.\n", "\n", "We need to keep the sum in a variable, so let's introduce a variable, say `result` (don't call it `sum`, as that is the name of the function.)\n", "\n", "Initially we set the result to 0. Then every time we encounter a new element, we increase the value of the result by the corresponding amount. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "result = 0\n", "\n", "for num in numbers:\n", " print(\"Processing number:\", num)\n", " result += num\n", " print(\"The current sum is\", result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Finding the Maximum" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see an example now, where we have a list of positive numbers and we want to find the largest one in the list.\n", "\n", "Here is an example list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = [40, 27, 50, 15, 32, 16, 31, 38, 45, 33]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, in most cases, to find the maximum element we can just write" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "max(numbers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "but we want now to see how we can find the maximum using a `for` loop.\n", "\n", "The first thing that we do is to create a variable (say, `maximum`) that contains the largest value we have seen so far.\n", "\n", "Initially, we can set it to -1, which is by definition smaller than any of the numbers that we will deal with (as we will only deal with positive numbers).\n", "\n", "Then, we go through all the numbers, using a for loop. If we find a number that is greater than the current `maximum` we change the value of maximum to be the new largest number that we encountered." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = [40, 27, 50, 15, 32, 16, 31, 38, 45, 33]\n", "\n", "maximum = -1\n", "for num in numbers: \n", " print(\"Processing number:\", num)\n", " if num > maximum:\n", " maximum = num\n", " print(\"We found a new maximum:\", maximum)\n", " print(\"The current maximum is:\", maximum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, notice that our code relies on the assumption that all elements are going to be positive. So, setting the maximum initially to -1 works.\n", "\n", "However, what happens if the assumption does not hold? Let's say that we want to find the smallest number in a list. \n", "\n", "Let's see how we can do that." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Finding the Minimum" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's change now the problem, and try to find the minimum. We will take our prior code and change `maximum` to `minimum` and then change the comparison from ` if num > maximum:` to `if num threshold:\n", " count = count + 1\n", " print(\"We found a number above\", threshold, \"and we increased count to\", count)\n", "\n", "print(\"We have\", count, \"numbers above\", threshold)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Finding an element in the list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's say that we want to search a list of names to see if there is an element that contains a particular string.\n", "\n", "For example, we have the list of NBA teams, and we want to find the team that plays in _Brooklyn_.\n", "\n", "We will start by creating a `looking_for` variable for storing the value of `Brooklyn`.\n", "\n", "Then we will use the loop to to through the list of teams, to find whether any of the team names contains the `looking_for` string. \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nba_teams = [\n", " \"Atlanta Hawks\", \"Boston Celtics\", \"Brooklyn Nets\", \"Charlotte Hornets\",\n", " \"Chicago Bulls\", \"Cleveland Cavaliers\", \"Dallas Mavericks\",\n", " \"Denver Nuggets\", \"Detroit Pistons\", \"Golden State Warriors\",\n", " \"Houston Rockets\", \"Indiana Pacers\", \"LA Clippers\", \"Los Angeles Lakers\",\n", " \"Memphis Grizzlies\", \"Miami Heat\", \"Milwaukee Bucks\",\n", " \"Minnesota Timberwolves\", \"New Orleans Pelicans\", \"New York Knicks\",\n", " \"Oklahoma City Thunder\", \"Orlando Magic\", \"Philadelphia 76ers\",\n", " \"Phoenix Suns\", \"Portland Trail Blazers\", \"Sacramento Kings\",\n", " \"San Antonio Spurs\", \"Toronto Raptors\", \"Utah Jazz\", \"Washington Wizards\"\n", "]\n", "print(\"The list contains\", len(nba_teams), \"teams\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "looking_for = \"Brooklyn\"\n", "for team in nba_teams:\n", " if looking_for in team: \n", " print(\"We found the team:\", team, \"containing\", looking_for)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's say that we want to store the team name that contains the string `looking_for`, so that we can reuse it later. We will store the result in the `result` variable.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "looking_for = \"Brooklyn\"\n", "\n", "result = None\n", "for team in nba_teams:\n", " if looking_for in team: \n", " result = team\n", " print(\"We found the team:\", team, \"containing\", looking_for)\n", " \n", "print(\"Result:\", result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that it is not possible to skip creating the `result` variable, if we want to keep the value of the team that we are looking for outside the loop." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Notice that we get an incorrect result if we assume that `team` will contain the answer\n", "# The loop will continue running\n", "looking_for = \"Brooklyn\"\n", "for team in nba_teams:\n", " if looking_for in team: \n", " print(\"We found the team:\", team, \"containing\", looking_for)\n", " \n", "print(\"Result:\", team)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now notice what would happen if we look for the term \"New\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "looking_for = \"New\"\n", "for team in nba_teams:\n", " if looking_for in team: \n", " result = team\n", " print(\"We found the team:\", team, \"containing\", looking_for)\n", " \n", "print(\"Result:\", result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This time we find two teams during our loop that pop up matching ‘new’, the pelicans and knicks, but at the end, result only contains ‘knicks’.\n", "This is because result stores only the last variable.\n", "\n", "What can we do if we have multiple results matching, we need to do something to hold multiple results. Let’s see another common pattern next, where we process one list and the result will be another list\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating a new list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's see now another pattern that we are frequently using: Process _all_ the elements of a list to generate another list.\n", "\n", "We will use our example with the NBA teams and franchises, that we examined earlier. This time, instead of just printing out the results, we will store the franchise names in a new list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nba_teams = [\n", " \"Atlanta Hawks\", \"Boston Celtics\", \"Brooklyn Nets\", \"Charlotte Hornets\",\n", " \"Chicago Bulls\", \"Cleveland Cavaliers\", \"Dallas Mavericks\",\n", " \"Denver Nuggets\", \"Detroit Pistons\", \"Golden State Warriors\",\n", " \"Houston Rockets\", \"Indiana Pacers\", \"LA Clippers\", \"Los Angeles Lakers\",\n", " \"Memphis Grizzlies\", \"Miami Heat\", \"Milwaukee Bucks\",\n", " \"Minnesota Timberwolves\", \"New Orleans Pelicans\", \"New York Knicks\",\n", " \"Oklahoma City Thunder\", \"Orlando Magic\", \"Philadelphia 76ers\",\n", " \"Phoenix Suns\", \"Portland Trail Blazers\", \"Sacramento Kings\",\n", " \"San Antonio Spurs\", \"Toronto Raptors\", \"Utah Jazz\", \"Washington Wizards\"\n", "]\n", "print(\"The list contains\", len(nba_teams), \"teams\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we create an empty list `franchise_names = []` where we are going to store the franchise names for the different teams. So, instead of printing the franchise name, we will add it to the `franchise_names` list. So, we will change our earlier loop:\n", "\n", "```python\n", " for team in nba_teams:\n", " franchise = team.split()[-1]\n", " print(team, \"\\t ==>\\t\", franchise)\n", "```\n", "\n", "into the following:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "franchise_names = []\n", "for team in nba_teams:\n", " franchise = team.split()[-1]\n", " # print(team, \"\\t ==>\\t\", franchise)\n", " franchise_names.append(franchise)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So this loop does not print anything out, but instead appends each team name into the `franchise_names` list. \n", "Once we execute the loop, we can then print out the names of the teams:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the list\n", "print(franchise_names)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Or use a loop to print each name in a separate line \n", "print(\"List of NBA franchise names\")\n", "for franchise_name in franchise_names:\n", " print(franchise_name)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 2 }