CS 115 Lab 10, Part B: Linear search

[Back to lab instructions]


Instructions

  1. Make a copy of your lab10a.py file. Name it lab10b.py.
  2. Add the following function definition to your program:
    def linear_search(search_list, value_to_find):
        """
        Uses a hand-coded linear search to find the position of an item in a list
    
        Parameters: the list; the item to search for
        Returns: the position of the item in the list 
            (or None if it is not in the list)
        """
        pass
    
  3. Write code in linear_search to do the following. (Note: do NOT use the search_list.index() method function. We are trying to duplicate what the index() method function does, by writing our own code.) You do not need to explicitly return None, but you should make sure that your code does not return anything if the item is not in the list.
  4. In main, add code to your loop to do the following:
  5. Make sure your code matches the sample inputs and outputs below exactly (except for the etc.), including the blank lines:
    Name of input file: cities.txt
    Number of lines in file: 50
    0: Los Angeles
    1: San Diego
    2: San Jose
    3: San Francisco
    [etc]
    
    Enter the name of a city: Santa Rosa
    The position of Santa Rosa is:
    Linear search: 25
    
    Enter the name of a city: Oakland
    The position of Oakland is:
    Linear search: 7
    
    Enter the name of a city: Cotati
    The position of Cotati is:
    Linear search: None
    
    Enter the name of a city: quit
  6. Answer Question 9 in your writeup, using cities.txt as the input file.
  7. Comment out the line of code that prints the number of lines in the input file.
  8. Continue to Part C.