Advertisement
Antypas

Linear search sorted list

Apr 18th, 2020
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. #Linear Search Sorted list
  2.  
  3. from random import randint
  4. sequence = [randint(0,10) for i in range(30)]
  5.  
  6. #sequence = ['a', 'C', 'B', 'A', 'c']
  7. sorted_sequence = sorted(sequence)
  8. print(sorted_sequence)
  9.  
  10. def linear_search(sorted_sequence, value):
  11.     for position, item in enumerate(sorted_sequence):
  12.         if item == value:
  13.             print(item, "is at position", position)
  14.             return position
  15.             #this causes program to stop once the desired item is found;
  16.             #does not continue searching for more occurrences of desired item.
  17.         elif item > value:
  18.             print("We've already exceeded desired value {} with no success".format(value))
  19.             return False
  20.         elif position == len(sorted_sequence)-1:
  21.             print(value, "is not in the sequence")
  22.             return False
  23. #temp = linear_search(sorted_sequence, 'C')
  24. temp = linear_search(sorted_sequence, 7)
  25. print(temp)
  26.  
  27. #temp = linear_search(sorted_sequence, 'F')
  28. temp = linear_search(sorted_sequence, 14)
  29. print(temp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement