Advertisement
richbpark

Linear Search Examples

Feb 9th, 2019
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. sequence = ['A','B','C','D','E','F']
  2. print('The sequence is', sequence , '\n')
  3.  
  4. # The enumerate function maps a number to each list item,
  5. # and does not need a separate counter variable.
  6. # It also allows some clever things.
  7. # ie. example enumerate(sequence,1) labels
  8. # each element starting at 1 rather than 0.
  9. print("The entire list.\n")
  10. for position, item in enumerate(sequence,1):
  11. print(item, " is at position ", position,".", sep="")
  12. print('\n\n')
  13.  
  14. print('Using a while loop to search for the \'C\'.')
  15. #Example 1 - A while loop
  16. position = 0
  17. while position < len(sequence):
  18. if (sequence[position] == 'C'):
  19. print(sequence[position], " is at position ", str(position + 1),".", sep="")
  20. position += 1
  21.  
  22. print('\n')
  23. print('Using a for loop to search for the \'F\'.')
  24. #Example 2 - A for loop over a range
  25. for position in range(len(sequence)):
  26. if (sequence[position] == 'F'):
  27. print(sequence[position], " is at position ", str(position + 1),".", sep="")
  28.  
  29. print('\n')
  30. print('Using the Python enumerate function to search for \'B\'.')
  31. #Example 3 - The enumerate function
  32.  
  33. for position, item in enumerate(sequence,1):
  34. if (item == 'B'):
  35. print(item, " is at position ", position,".","\n\n", sep="")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement