Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #linear search through a sorted list, takes a random list, makes copy, sorts it, then searches
- numbers = [1,2,5,8,7,9,12,51,41,87,95,98,992,52,472,21,43]
- def sort_search(list_to_search,find):
- sortedlist = (list_to_search[:]) #create new list,a copy of (list_to_search), leave old intact
- sortedlist.sort() #sort new list
- print(sortedlist)
- for position in range(len(sortedlist)):
- if find == sortedlist[position]:
- print("Object " + str(find) + " is at position " + str(position + 1))
- break #is there other way to stop loop?
- elif position + 1 == len(sortedlist) or find < (sortedlist[position]):
- print("Not found")
- break #break to stop loop, position = len(sortedlist) + 1 does not stop loop
- else:
- position = position + 1
- sort_search(numbers,53)
- def sort_search2(list_to_search,find):
- sortedlist = (list_to_search[:]) #create new list,a copy of (list_to_search), leave old intact
- sortedlist.sort() #sort new list
- print(sortedlist)
- position = 0
- search = True
- while search == True: #while statement is true, loop wil run
- search = False #sets search to false, so that if 1 of 3 conditions is met loop ends
- if find == sortedlist[position]:
- print("Object " + str(find) + " is at position " + str(position + 1))
- elif position + 1 == len(sortedlist) or find < (sortedlist[position]):
- print("Not found")
- else:
- position = position + 1 #if 1 of 3 conditions is not met loop set to true
- search = True
- sort_search2(numbers,472)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement