Using Python to achieve dichotomy: my approach to implementation is as follows
1, determine whether the value to find is greater than the maximum value, if greater than the direct return false
2, determine whether the value to find is less than the minimum value, if less than the direct return false
3. If the value you are looking for is between the maximum and the minimum value, enter the loop
A, the first sequence is longer than 1, and then gets the size of a value in the middle of the sequence.
b, and then compare to the value to be looked up, if equal, returns true if not equal, if the middle value is greater than the value to find, then the value to find is on the left side of the middle value, if the middle value is less than the value to find, then the value to find is the right side of the middle value
C, finally, if the length of the sequence is 1, the value of the sequence is determined directly and the value to be found is equal.
def f1 (src_list,find_n): If Find_n > Src_list[-1]: #判断find_n是否大于最大值, if greater then return directly s = "%s is not finded"% (find_n) print (s) return False if Find_n < Src_list[0]: #判断find_n是否小于最小值, if less than the direct return s = "%s is not finded"% (find_n) print (s) return False else : #只有find_n在最大值和最小值之间 before entering function mid = Int (len (src_list)/2) if Len (src_list) > 1:if Src_list[mid] > Find_n:print ("%s in left"% (find_n)) Mid_list = Src_list[0:mid] F1 (mid_list,find_n) elif Src_list[mid] < find_n:p Rint ("%s in right"% (find_n)) Mid_list = Src_list[mid:] F1 (mid_list,find_n) Else: Print ("%s is finded"% (find_n)) return True If Len (src_list) = = 1:if src _list[0] = = Find_n: s = "%s is finded"% (find_n) print (s) return True else: s = "%s is not finded"% (find_n) print (s) return falsedata = List (range (0,10,3)) F1 (data,- 1)
Using Python to achieve binary method