Advertisement
kevinbocky

linear_search_sorted.py

Jan 30th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. #linear search through a sorted list, takes a random list, makes copy, sorts it, then searches
  2. numbers = [1,2,5,8,7,9,12,51,41,87,95,98,992,52,472,21,43]
  3.  
  4. def sort_search(list_to_search,find):
  5. sortedlist = (list_to_search[:]) #create new list,a copy of (list_to_search), leave old intact
  6. sortedlist.sort() #sort new list
  7. print(sortedlist)
  8. for position in range(len(sortedlist)):
  9. if find == sortedlist[position]:
  10. print("Object " + str(find) + " is at position " + str(position + 1))
  11. break #is there other way to stop loop?
  12. elif position + 1 == len(sortedlist) or find < (sortedlist[position]):
  13. print("Not found")
  14. break #break to stop loop, position = len(sortedlist) + 1 does not stop loop
  15. else:
  16. position = position + 1
  17.  
  18.  
  19.  
  20. sort_search(numbers,53)
  21.  
  22.  
  23.  
  24.  
  25. def sort_search2(list_to_search,find):
  26. sortedlist = (list_to_search[:]) #create new list,a copy of (list_to_search), leave old intact
  27. sortedlist.sort() #sort new list
  28. print(sortedlist)
  29. position = 0
  30. search = True
  31. while search == True: #while statement is true, loop wil run
  32. search = False #sets search to false, so that if 1 of 3 conditions is met loop ends
  33. if find == sortedlist[position]:
  34. print("Object " + str(find) + " is at position " + str(position + 1))
  35. elif position + 1 == len(sortedlist) or find < (sortedlist[position]):
  36. print("Not found")
  37. else:
  38. position = position + 1 #if 1 of 3 conditions is not met loop set to true
  39. search = True
  40.  
  41. sort_search2(numbers,472)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement