elena_gancedo

Linear_search_resource

Sep 13th, 2019
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.07 KB | None | 0 0
  1. # linear search algorithm with function
  2. """
  3. Example of how to search an item with a linear
  4. search, selecting it from a list (things inside a bag)
  5. """
  6. # Python implementation:
  7. # ● Entries: a list and the searched item
  8. # ● Outputs: item position or an exception
  9. def linearSearch(item,my_list):
  10. # Returns a Boolean value that indicates whether the item is present or not
  11. # The Boolean variable found is initialized to False
  12.     found = False
  13.     position = 0 # position has the current position in the list, starts at 0
  14.     while position < len(my_list) and not found:
  15.         if my_list[position] == item:
  16. # It is assigned the True value if we discover the item in the list.          
  17.             found = True
  18.         position = position + 1
  19.     return found
  20. bag = ['book','pencil','pen','notebook','sharpener','rubber']
  21. print("Items in the bag: ", bag)
  22. item = input('What item do you want to check for in the bag?')
  23. itemFound = linearSearch(item,bag)
  24. if itemFound:
  25.     print 'Yes, the item is in the bag'
  26. else:
  27.     print 'Oops, your item seems not to be in the bag'
Advertisement
Add Comment
Please, Sign In to add comment