October 3: Loops

Learning Objectives

After today's class, you should be able to:

  • Use range() and enumerate()
  • Use a loop to find and count words in a dictionary.
  • Write a loop that computes the min, max, and sum.
  • Solve problems that compare previous/next values.

Lesson Outline

Mini Lecture: More on for loops

Inclass Activity

  1. Given a string, print each uppercase letter along with its index. Ex: print_upper("James Madison Computer Science") should print:
    J at 0
    M at 6
    C at 14
    S at 23
    
  2. Given a sentence, count how many times each word occurs. Use a dictionary to keep track of the count of each word. Ex: count_words("mat the cat sat on the mat") should return:
    {'mat': 2, 'the': 2, 'cat': 1, 'sat': 1, 'on': 1}
    

Min, Max, Sum

  • the built-in functions min(), max(), sum() require a loop
  • calling sum(grades)/max (grades) runs two loops
    def my_min(sequence):
        result = sequence[0]
        for value in sequence:
            if value < result:  # found new minimum
              result = value
     return result

    def my_max(sequence):
        result = sequence[0]
        for value in sequence:
            if value > result:  # found new maximum
                result = value
        return result

    def my_sum(sequence):
        result = 0
        for value in sequence:
            result += value     # add running total
        return result


    if __name__ == "__main__":
        print("min:", my_min([13, -5, 100, 0, 77]))
        print("max:", my_max([13, -5, 100, 0, 77]))
        print("sum:", my_sum([13, -5, 100, 0, 77]))

3. Find the index of the maximum value in a list. Ex. index_max([13, -5, 100, 0, 77]) returns 2.

4. Count how characters in a string are digits. Ex. count_digits("Today is 10/03/2023!") returns 8

Looking Ahead

  • Sometimes a loop needs to look at index [i + 1].
  • In that case, the range should end at len(s) - 1.
def is_sorted(seq):
    for i in range(len(seq) - 1):
         if seq[i] > seq[i + 1]:
            return False
    return True

if __name__ == "__main__":
    print("yes sorted:", is_sorted([1, 5, 10, 13, 16]))
    print("not sorted:", is_sorted([1, 5, 13, 16, 10]))

5. Write a function, two_in_row, that returns True if two consecutive values are equal. Ex. two_in_row(["Pizza", "Soda", "Soda", "Candy", "Salad"]) returns True.

6. Write a function, three_in_row, that returns True if three consecutive values are equal. Ex. three_in_row(["Apple", "Banana", "Cherry", "Cherry", "Cherry"]) returns True.

Extra Practice

CodingBat.com is a free site of live problems to build skill in Java and/or Python. CodingBat was created by Nick Parlante, who is Computer Science lecturer at Stanford.

Note: Do not use the built-in min(), max(), sum() for any of these problems.

List-2 Problems

  • 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

*Thanks to Dr. Mayfield for these exercises

Your To-Do List

Due Wednesday October 4th at 11pm*

  • Submit HW 6 through Canvas and check out the Help page. Remember the attribution statement

Prepare for Quiz 3A

  • Thursday, beginning of class, 25 minutes, in EnGeo 2204.
  • Two parts: concepts and programming (will use lab machine account, canvas and gradescope)
  • Study chapters 5 and 6: both reading and activities
  • Review class activities
  • Review homework programming assignments By today

  • Start Chapter 7 "orange" textbook activities

  • Start Homework 7: HW 7

Complete by Monday October 9th

Due Wednesday October 11th at 11pm