Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # linear search algorithm with function
- """
- Example of how to search an item with a linear
- search, selecting it from a list (things inside a bag)
- """
- # Python implementation:
- # ● Entries: a list and the searched item
- # ● Outputs: item position or an exception
- def linearSearch(item,my_list):
- # Returns a Boolean value that indicates whether the item is present or not
- # The Boolean variable found is initialized to False
- found = False
- position = 0 # position has the current position in the list, starts at 0
- while position < len(my_list) and not found:
- if my_list[position] == item:
- # It is assigned the True value if we discover the item in the list.
- found = True
- position = position + 1
- return found
- bag = ['book','pencil','pen','notebook','sharpener','rubber']
- print("Items in the bag: ", bag)
- item = input('What item do you want to check for in the bag?')
- itemFound = linearSearch(item,bag)
- if itemFound:
- print 'Yes, the item is in the bag'
- else:
- print 'Oops, your item seems not to be in the bag'
Advertisement
Add Comment
Please, Sign In to add comment