A search is when you iterate through a collection, looking for values that meet a given critera.
They usually involve
We've used this pattern for solving several different kinds of problems.
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for day in days_of_the_week:
if "S" not in day:
print(day,"is a good day for programming")
min() and max()¶The built-in min() and max() algorithms can find the largest or smallest value in a list.
my_list = [5,1,8,7,4,2]
max(my_list)
How do you think this function works?
It's set up using this search pattern.
Think about how you'd remember the largest value in a list of numbers.
student_grades = [88.3, 53.2, 76.6, 92.2, 81.9, 79.7, 62.1, 84.8, 83.3]
student_grades[8]
What was the biggest grade in that list?
At each step, you remembered what the max-so-far was, and you compared it with the new value. At the end, whatever your max-so-far is, is the max of the whole list.
Let's code this up.
student_grades = [88.3, 53.2, 76.6, 92.2, 81.9, 79.7, 62.1, 84.8, 83.3]
#in-class demo here
#solution 1
max_so_far = -float("inf") #Python's representation of "negative infinity"
for grade in student_grades:
#if I found a new max-so-far
if grade > max_so_far:
#keep track of this value as the new max-so-far
max_so_far = grade
print("The max grade is",max_so_far)
#solution 2
#in this version we start the max_so_far as the first item in the list
max_so_far = student_grades[0]
for grade in student_grades:
if grade > max_so_far:
max_so_far = grade
print("The max grade is",max_so_far)
What changes do we need to make if we want to find the minimum instead of the maximum?