Advertisement
brendan-stanford

linear_search

Aug 25th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. from random import randint
  2.  
  3. #randomly generated list of size specified by user
  4. n_list = [randint(1, 100) for i in range(int(input("Size of random number list:")))]
  5.  
  6. #demo list for testing value recognition
  7. #n_list = [5,3,4,1,2]
  8.  
  9. '''#linear search: FOR loop; searches sequence list and if value matches, returns position+1 for human recognition; otherwise False
  10.  
  11. def linear_search(sequence, value):
  12. n = len(sequence)
  13. for position in range(n):
  14. print(sequence[position], "is at position", str(position+1))
  15. if sequence[position] == value:
  16. return position+1
  17. elif position == (n-1) and sequence[position] != value:
  18. return False
  19. '''
  20.  
  21. #linear search: ENUMERATE loop; searches sequence list and if value matches returns exact position (already increase by 1 in enumerate); otherwise False
  22.  
  23. def linear_search(sequence, value):
  24. n = len(sequence)
  25. for position, item in enumerate(sequence,1):
  26. print(item, "is at position", position)
  27. if item == value:
  28. return position
  29. elif position == n and item != value:
  30. return False
  31.  
  32.  
  33. #collects user guess for value to search for and feeds into linear_search function; stores result in search variable
  34. guess = int(input("Number to search list for:"))
  35. search = linear_search(n_list, guess)
  36.  
  37. #prints success or failure message
  38. if search != False:
  39. print(str(guess), "was found at position", search)
  40. else:
  41. print(str(guess), "is not in the list!")
  42.  
  43. #print list for visual inspection outside of function
  44. #print(n_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement