Python implements Binary Search Algorithm Instances and python Algorithms
This example describes how to implement the Binary Search Algorithm in Python. Share it with you for your reference. The specific implementation method is as follows:
#! /Usr/bin/env pythonimport sys def search2 (a, m): low = 0 high = len (a)-1 while (low <= high ): mid = (low + high)/2 midval = a [mid] if midval <m: low = mid + 1 elif midval> m: high = mid-1 else: print mid return mid print-1 return-1if _ name _ = "_ main _": a = [int (I) for I in list (sys. argv [1])] m = int (sys. argv [2]) search2 (a, m)
Run:
Administrator @ ubuntu :~ /Python $ python test_search2.py 123456789 4
3
Note:
1. '_': Because python class members are both public and publicly accessible and public, there is a lack of private attributes like the Orthodox object-oriented language.
So we will use _ to simulate private attributes. These _ attributes are often used internally and generally do not need to be rewritten. No need to read.
The purpose of adding two underscores (_) is not to conflict with the names of common public properties, or to prevent users (non-developers) of objects from using them at will.
2. _ name _ = "_ main _" indicates that the script is directly executed.
If the value is not equal to, the script is imported by other programs using import. The _ name _ attribute is set as the module name.
I hope this article will help you with Python programming.