scipiguy

Programming 102: Linear Search

Jun 28th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. def linearSearch(query, sequence):
  2.     found = False
  3.     for position, item in enumerate(sequence, 1):
  4.         if item == query:
  5.             print("Found " + str(query) + " at position " + str(position))
  6.             found = True
  7.     if found == False:
  8.         print("The number " + str(query) + " was not found.")
  9.     return found
  10.  
  11. def linearSearchWhile(query, sequence):
  12.     found = False
  13.     position = 0
  14.     while found == False and position < len(sequence):
  15.         if sequence[position] == query:
  16.             found = True
  17.             print("Found " + str(query) + " at position " + str(position))
  18.         position += 1
  19.     if found == False:
  20.         print("The number " + str(query) + " was not found.")
  21.  
  22. sequence = [1, 5, 9, 11, 2, 0, 8]
  23.  
  24. query = int(input("Which number is required in your linear search? "))
  25. linearSearch(query, sequence)
  26.  
  27. sequence.sort()
  28. query = int(input("Which number is required in your sorted 'While' linear search? "))
  29. linearSearchWhile(query, sequence)
Advertisement
Add Comment
Please, Sign In to add comment