Sep 30: Solving Problems with Loops
Learning Objectives
After today's class, you should be able to:
- 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.
Reminders¶
for
Statements¶
- See the examples from Wednesday and the activity from Friday.
- Use variable names that match the type of loop (not just
for 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 |
for key in my_dict: |
For each key in a dict |
for key, value in my_dict.items(): |
For each key and value |
Exercise
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
Exercise
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
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.
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.
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()
, or sum()
functions for any of these problems.
- Easier: count_evens, has22
- Medium: big_diff, sum13
- Harder: centered_average, sum67
- Easier: double_char, count_hi
- Medium: count_code, cat_dog
- Harder: xyz_there, end_other