Python Search List
Python search list.
- Un-ordered list search
- Ordered list search
Python unordered list search
#Python search list items = [9, 35, 56, 23, 12, 45, 765, 32, 44, 29, 12, 9] #sorting unordered list def find_items(item, item_list): for i in range(0, len(items)): if item == item_list[i]: return i return None print(find_items(23, items)) print(find_items(45, items))
#----------------------------------------------------------------------------
#Output
3 5
#sorting ordered list ordered_items = [3, 4, 6, 7, 34, 56, 77, 83, 89, 656, 4445] def binary_search(item, item_list): #get list size list_size = len(item_list) - 1 #start at the end of the list lower_index = 0 upper_index = list_size while lower_index <= upper_index: #calculate the middle point mid_point = (lower_index + upper_index) // 2 #if item is found, return index if item_list[mid_point] == item: return mid_point #otherwise get the nexr midpoint if item > item_list[mid_point]: lower_index = mid_point + 1 else: upper_index = mid_point - 1 if lower_index > upper_index: return None print(binary_search(7, ordered_items)) print(binary_search(656, ordered_items))
#-------------------------------------------------------------------------------
#Output
3
9
Comments
Post a Comment