Advertisement
timber101

LieralSearchUnsortedAndSOrtedList

Dec 28th, 2020
620
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None
  1. #  literal search on unsorted and sorted list
  2.  
  3. sequence = ['A','B','C','D']
  4.  
  5. my_list = [2,4,1,6,5] # an unsorted list
  6.  
  7. my_list_sorted = [1,2,3,5,6] # sorted list
  8.  
  9.  
  10. def whilesearch(alist, avalue):
  11.     print("using whilesearch function")
  12.     found = False
  13.     pos = 0
  14.     while pos < len(alist):
  15.         if alist[pos] == avalue:
  16.             print(alist[pos], "is at position", str(pos))
  17.             found = True
  18.             break
  19.         else:
  20.             pos += 1
  21.            
  22.     if not found:        
  23.         print(f"{avalue} not found")
  24.    
  25. whilesearch(my_list, 6)
  26.  
  27.  
  28.  
  29. def whilesearchsorted(alist, avalue):
  30.     print("using whilesearchsorted function")
  31.     found = False
  32.     pos = 0
  33.     while pos < len(alist) and not found:
  34.         if alist[pos] > avalue:
  35.             break
  36.         elif alist[pos] == avalue:
  37.             print(alist[pos], "is at position", str(pos))
  38.             found = True
  39.             break
  40.         else:
  41.             pos += 1
  42.            
  43.     if not found:        
  44.         print(f"{avalue} not found")
  45.    
  46. whilesearchsorted(my_list_sorted, 4)
  47.  
Advertisement
RAW Paste Data Copied
Advertisement