Advertisement
GCK

GCK/ linear search on sorted list

GCK
Oct 1st, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.58 KB | None | 0 0
  1. from random import randint
  2.  
  3. # this function will first sort a list and then apply the linear search by stopping at whenever item in list is bigger than value
  4.  
  5. my_list2=[190, 496, 165, 371, 317, 307, 990, 303, 35, 598, 546, 969, 774, 418,
  6.           855, 956, 340, 578, 639, 417, 225, 741, 579, 227, 414, 112, 252, 254,
  7.           637, 295, 324, 408, 601, 831, 767, 340, 193, 38, 498, 95, 39, 690,
  8.           920, 321, 74, 80, 878, 728, 381, 28, 558, 477, 405, 311, 216, 820,
  9.           85, 95, 884, 425, 927, 471, 586, 690, 1000, 169, 899, 48, 661, 522,
  10.           130, 379, 948, 459, 999, 263, 62, 182, 663, 533, 84, 110, 360, 974,
  11.           95, 763, 728, 622, 500, 337, 693, 320, 864, 107, 77, 103, 776, 981,
  12.           625, 350]
  13.  
  14. def linear_search_sortedlist(my_list2,value):
  15.     my_list2_sorted=sorted(my_list2)
  16.     print(my_list2_sorted)
  17.     count=0
  18.     position_list=[]
  19.  
  20.            
  21.     for i in range(len(my_list2_sorted)):
  22.                
  23.         if  my_list2_sorted[i ]<= value:
  24.             #print("im here")
  25.            
  26.             if my_list2_sorted[i] == value:
  27.                    
  28.                 count+=1 # if item is several time there
  29.                 position_list.append(i)
  30.                 #print("item {} is at position(s) {} thus is found {} time(s)".format(value,i, count))                    
  31.            
  32.         else:
  33.             print("from i= {} it's above {}. We stop".format(i,value))
  34.             return False, position_list
  35.  
  36. end,search3=linear_search_sortedlist(my_list2,95)
  37. value=95
  38. print("Position lists for {} is {}".format(value,search3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement