Advertisement
brendan-stanford

linear_search_sorted

Aug 25th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 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. #sorted function called to sort n_list and store as s_list
  10. s_list = sorted(n_list)
  11.  
  12. '''#linear search: FOR loop; searches sequence list and if value matches, returns position+1 for human recognition; otherwise False
  13.  
  14. def linear_search(sequence, value):
  15. n = len(sequence)
  16. for position in range(n):
  17. print(sequence[position], "is at position", str(position+1))
  18. if sequence[position] == value:
  19. return position+1
  20. elif position == (n-1) and sequence[position] != value:
  21. return False
  22. elif sequence[position] > value:
  23. return False
  24. '''
  25.  
  26. #linear search: ENUMERATE loop; searches sequence list and if value matches returns exact position (already increase by 1 in enumerate); otherwise False
  27.  
  28. def linear_search(sequence, value):
  29. n = len(sequence)
  30. for position, item in enumerate(sequence,1):
  31. print(item, "is at position", position)
  32. if item == value:
  33. return position
  34. elif position == n and item != value:
  35. return False
  36. elif item > value:
  37. return False
  38.  
  39.  
  40. #collects user guess for value to search for and feeds into linear_search function; stores result in search variable
  41. guess = int(input("Number to search list for:"))
  42. search = linear_search(s_list, guess)
  43.  
  44. #prints success or failure message
  45. if search != False:
  46. print(str(guess), "was found at position", search)
  47. else:
  48. print(str(guess), "is not in the list!")
  49.  
  50. #print lists for visual inspection outside of function
  51. print(n_list)
  52. print(s_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement