Want to receive a weekly email containing
the scoop on our new titles along with the
occasional special offer? Just click the button.
(You can always unsubscribe later by editing your
account information).

Give us an email and a password (you can use the password later to log in and
change your preferences). We'll send you a newsletter roughly once a week.

PracProg2searchsort

1.

While loop version:

def linear_search(lst, value):
""" (list, object) -> int
Return the index of the last occurrence of value in lst, or return
-1 if value is not in lst.
>>> linear_search([2, 5, 1, -3], 5)
1
>>> linear_search([2, 4, 2], 2)
2
>>> linear_search([2, 5, 1, -3], 4)
-1
>>> linear_search([], 5)
-1
"""
i = len(lst) - 1 # The index of the next item in lst to examine.
# Keep going until we reach the end of lst or until we find value.
while i != -1 and lst[i] != value:
i = i - 1
# If we fell off the end of the list, we didn't find value.
if i == -1:
return -1
else:
return i

For loop version:

def linear_search(lst, value):
""" (list, object) -> int
Return the index of the last occurrence of value in lst, or return
-1 if value is not in lst.
>>> linear_search([2, 5, 1, -3], 5)
1
>>> linear_search([2, 4, 2], 2)
2
>>> linear_search([2, 5, 1, -3], 4)
-1
>>> linear_search([], 5)
-1
"""
# The first index is included, the second is not, and the third is the
# increment.
for i in range(len(lst) - 1, -1, -1):
if lst[i] == value:
return i
return -1