Using Python to achieve binary method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.