Oct 02: Solving Problems with Loops
Meet in King 248
Learning Objectives
After today's class, you should be able to:
- Use a loop to accumulate or filter values into a new list.
- Write a loop that computes the min, max, and sum of a list.
- Modify a list with
append(), index assignment, removal, and sort.
Lesson Outline
Presentation [10 min]
- Editing lists (appending, assignment, removal, sorting)
Loop Problems [40 min]
- I'll explain each section below, and you'll solve the problems
Your To-Do List
for Statements
- See the examples from Monday and the activity from Wednesday.
- Variable name should match the type of loop (don't always use
i)
| Code | Meaning |
|---|---|
for value in my_list: |
For each value in a list |
for index in range(len(my_list)): |
For each index in a list |
for index, value in enumerate(my_list): |
For each index and value |
Exercise
Given a string, print each uppercase letter along with its index.
Hint: use the str.isupper() method.
Ex: print_upper("James Madison Computer Science") should print:
J at 0
M at 6
C at 14
S at 23
Exercise
Given a positive integer n, build a list of all numbers from 1 to n that are divisible by 3 or 5.
Use range() to loop over the numbers, and append() each one that matches.
Ex: multiples(20) should return:
[3, 5, 6, 9, 10, 12, 15, 18, 20]
Min, Max, Sum
- The built-in
min(),max(), andsum()functions require a loop. - Therefore, 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]))
Exercise
Find the index of the maximum value in a list.
Ex: index_max([13, -5, 100, 0, 77]) returns 2, because the maximum value 100 is at index 2.
Exercise
Count how many characters in a string are digits.
Hint: use the str.isdigit() method.
Ex: count_digits("Today is 10/02/2023!") returns 8, because 8 of the characters are digits.
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]))
Exercise
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 because of two "Soda" in a row.
Exercise
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 because of three "Cherry" in a row.