Advertisement
pamalau

Untitled

Feb 20th, 2019
588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.32 KB | None | 0 0
  1. from timeit import timeit
  2. from random import randint
  3. import matplotlib.pyplot as plt
  4. import logging
  5.  
  6. num_iterations = 500
  7.  
  8. def linear_search (a_list, an_item):
  9.     result = -1 # an_item not found
  10.     for position, value in enumerate(a_list):
  11.         if value == an_item:
  12.             result = position
  13.             break
  14.         if value > an_item:
  15.             break    
  16.     return position          
  17.    
  18. def binary_search(sorted_list, item_to_find):
  19.     left = 0
  20.     list_len = len(sorted_list) - 1
  21.     right = list_len
  22.     result = False
  23.     num_iter = 0;
  24.     pos_list = []
  25.     near_pos = -1
  26.     min_diff = 1e20
  27.    
  28.     while left <= right:
  29.         num_iter +=1
  30.         mid = int((left + right)/2)
  31.         diff = abs(sorted_list[mid]-item_to_find)
  32.         if diff < min_diff:
  33.             min_diff = diff
  34.             near_pos = mid
  35.         if sorted_list[mid] > item_to_find:
  36.             right = mid - 1
  37.         elif sorted_list[mid] < item_to_find:
  38.             left = mid + 1
  39.         else:
  40.             result = True
  41.             break
  42.     if result: #Check for multiples
  43.         pos_list.append(mid)
  44.         left = mid-1
  45.         while (sorted_list[left] == item_to_find) and (left >= 0):
  46.             pos_list.append(left)
  47.             left -= 1
  48.         right = mid + 1    
  49.         if right <= list_len:    
  50.             while (right <= list_len) and (sorted_list[right] == item_to_find):
  51.                 pos_list.append(right)
  52.                 right += 1
  53.         pos_list = sorted(pos_list)
  54.     #print('result='+str(result) + ' mid=' + str(mid) + ' sl='+str(sorted_list[mid]))
  55.     return result, sorted_list[mid], pos_list, num_iter, near_pos
  56.  
  57. def srch_times_for_list(a_list, list_len, l_list, b_list, percent):
  58.     if percent > 1:
  59.         num_to_find = list_len
  60.     else:
  61.         idx = (list_len-1) * percent
  62.         logging.debug('Idx = '+ str(idx))
  63.         #print('Idx = '+ str(idx))    
  64.         idx = int(idx)
  65.         if idx >= list_len:
  66.             idx = list_len -1;
  67.         #print('Idx = '+ str(idx))
  68.         num_to_find = a_list[idx]
  69.     #print("List Length = " + str(list_len) + " Searching for " + str(num_to_find) + " percent = " + str(percent))
  70.    
  71.     ls = lambda: linear_search(a_list, num_to_find)
  72.     bs = lambda: binary_search(a_list, num_to_find)
  73.     l_list.append(timeit(ls, number = num_iterations))
  74.     b_list.append(timeit(bs, number = num_iterations))
  75.     return l_list, b_list
  76. """
  77. list_to_search = [i for i in range(1000000)]
  78. ls = lambda: linear_search(list_to_search, randint(0,1000000))
  79. bs = lambda: binary_search(list_to_search, randint(0,1000000))
  80. """
  81.  
  82. #generate some data
  83. y=[]; x0l=[]; x0b=[]; x25l=[]; x25b=[]; x50l=[]; x50b=[]
  84. x75l=[]; x75b=[]; x100l=[]; x100b=[]; x105l=[]; x105b=[]
  85.  
  86. ii = 10
  87.  
  88. while ii <= 30000:
  89.     y.append(ii)
  90.     list_to_search = [ i for i in range(ii)]
  91.     x0l, x0b = srch_times_for_list(list_to_search,ii, x0l, x0b,0)
  92.     x25l, x25b = srch_times_for_list(list_to_search,ii, x25l, x25b,0.25)
  93.     x50l, x50b = srch_times_for_list(list_to_search,ii, x50l, x50b,0.50)
  94.     x75l, x75b = srch_times_for_list(list_to_search,ii, x75l, x75b,0.75)    
  95.     x100l, x100b = srch_times_for_list(list_to_search,ii, x100l, x100b,1.0)
  96.     x105l, x105b = srch_times_for_list(list_to_search,ii, x105l, x105b,1.05)
  97.     ii = ii + 2000
  98.    
  99. plt.style.use('seaborn-whitegrid')
  100. #fig1, (ax1, ax2, ax3, ax4) = plt.subplots(1,4 , sharex=True, sharey=True)
  101. fig1, (ax1, ax2) = plt.subplots(1,2 , sharey=True)
  102.  
  103. ax1.plot(x0l, y,  label='search[0%]')
  104. ax1.plot(x25l, y, label='search[25%]')
  105. ax1.plot(x50l, y, label='search[50%]')
  106. ax1.plot(x75l, y, label='search[75%]')
  107. ax1.plot(x100l, y, label='search[100%]')
  108. ax1.plot(x105l, y, label='not in list')
  109. ax1.legend(loc='lower right')
  110. ax1.set(xlabel='time (sec) ' + str(num_iterations) + ' Iterations', ylabel='Length of list (number of points)',
  111.        title='linear')
  112.  
  113. ax2.plot(x0b, y, label='search[0%]')
  114. ax2.plot(x25b, y, label='search[25%]')
  115. ax2.plot(x50b, y, label='search[50%]')
  116. ax2.plot(x75b, y, label='search[75%]')
  117. ax2.plot(x100b, y,label='search[100%]')
  118. ax2.plot(x105b, y,label='not in list')
  119. ax2.legend(loc='upper left')
  120. ax2.set(xlabel='time (sec) ' + str(num_iterations) + ' Iterations', ylabel='Length of list (number of points)',
  121.        title='binary')
  122.  
  123. fig1.set_size_inches(9.5, 8.5)    
  124. fig1.show()    
  125.  
  126.  
  127. print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement