Advertisement
GCK

GCK/ linear search

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