Exercises: Searching Lists
Apr 092018Before attempting these exercises, you should read the post on linear and binary search.
Exercises
- Add the following
print
statements to the linear search function as appropriate:print('Searching for the target', repr(target))
print('The value at index', i, 'is', repr(value))
print('The value equals the target')
print('The value does not equal the target')
print('The target was not found')
['the', 'cat', 'sat', 'on', 'the', 'mat']
as the input list, record the output when searching for'on'
,'dog'
and'the'
.
Use the interactive linear search model to check your results. - Add the following
print
statements to the binary search function as appropriate:print('Searching for the target', repr(target))
print('The range is from', left, 'to', right)
print('The value at index', middle, 'is', repr(value))
print('The value equals the target')
print('The value is less than the target')
print('The value is greater than the target')
print('The target was not found')
['all', 'bob', 'can', 'do', 'is', 'nap', 'zzz']
as the input list, record the output when searching for'is'
,'bob'
and'sleep'
.
Use the interactive binary search model to check your results. - The following Python code defines a class
User
and creates a list of users:
It is required to search for users either by name or by ID number.class User: def __init__(self, id_number, name): self.id_number = id_number self.name = name def __repr__(self): fmt = 'User({!r}, {!r})' return fmt.format(self.id_number, self.name) users = [ User(12, 'Waylon Dalton'), User(15, 'Justine Henderson'), User(20, 'Abdullah Lang'), User(28, 'Marcus Cruz'), User(45, 'Thalia Cobb'), User(46, 'Mathias Little'), User(51, 'Eddie Randolph'), User(60, 'Angela Walker'), User(63, 'Lia Shelton'), User(72, 'Hadassah Hartman'), User(78, 'Joanna Shaffer'), User(95, 'Jonathon Sheppard') ]
- Write a function using the linear search algorithm to search by name.
- The list is ordered by ID number. Write a function using the binary search algorithm to search by ID number.
User
object found by the search, orNone
if the search is unsuccessful.
Comments