First, recursion
Concept:
function calls the procedure of its own algorithm directly or indirectly, the function is called a recursive function. In computer programming, recursive algorithm is very effective to solve a large class of problems.
Characteristics:
① recursion is the invocation of itself in a procedure or function.
② when using a recursive strategy, there must be an obvious end condition , called a recursive exit. The problem size is less than the last recursion,
③ recursive algorithm is usually very concise, but the recursive algorithm is less efficient in solving problems. Therefore, we generally do not advocate the use of recursive algorithm design program.
④ in the process of recursive invocation, each layer of the system's return points, local variables, etc. open up a stack to store. Too many recursive functions tend to cause stack overflow and so on.
Therefore, the recursive algorithm is generally not advocated for the design of the program.
Requirements:
The recursive algorithm embodies the "repetition" generally has three conditions:
The ① is scaled down (usually halved) every time the call is scaled.
② There is a close connection between two repetitions, the previous one to be prepared for the next (usually the previous output as the last input).
③ must use direct answers instead of recursive calls when the scale of the problem is minimal, so that each recursive invocation is conditional (with the size not reaching the direct solution),
An unconditional recursive call will become a dead loop and not end normally.
Analyze the execution of the following functions:
def func3 (x): if x>0: print (x) func3 (x-1) func3 (5) def func4 (x): if x>0: func4 (x-1) Print (x) Func4 (5)
The execution results are analyzed according to the procedure executed by Python and the function call!
About the Fibonacci sequence
The Fibonacci sequence refers to a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368.
Special Note: The No. 0 item is 0, and the 1th item is the first 1. This sequence starts with the 2nd item and each item is equal to the sum of the first two items.
def Fibo (n): = 0 = 1 ifor n = =1 :return nif N <= 3: return 1 return Fibo (n-1) +fibo (n-2) Print(Fibo (3))
Fibonacci SequenceTwo-point Search
Starting from the candidate area Data[0:n] of the ordered list , the candidate area can be halved by comparing the value of the lookup with the median of the candidate area.
Characteristics:
The binary search algorithm is to continuously divide the array into halves, comparing the intermediate elements with the elements to be searched. Small on the right to find, big left to look for!
Requirements:
Within a number, find the median and determine the comparison between the value to be found and the median value.
If the median value is larger, the left-hand area of the median value continues to be found in the above way.
If the median value is smaller, the right-hand area of the median value continues to be found as described above.
Until we find the numbers we want.
defSearch_data (data,data_find):#definition of an index number for an intermediate value: Array length/2mid = Int (len (data)/2) #Judging from the 1-based array of numbers found in ifData[mid] >= 1: #If we're looking for a value (data_find) smaller than the median (Data[mid]) ifData[mid] >Data_find:Print("the number you are looking for is smaller than the median value [%s] ..."%Data[mid])#continue to find on the left side of the median (Data[mid]) and continue looping in this functionsearch_data (Data[:mid],data_find)#If we're looking for a value (Data_find) larger than the median (Data[mid]) elifData[mid] <Data_find:Print("the number you are looking for is larger than the median value [%s] ..."%Data[mid])#continue the lookup on the right side of the median (Data[mid]) and continue looping in this functionsearch_data (Data[mid:],data_find)Else: #If we are looking for a value (Data_find) that is neither larger than the median (Data[mid]) or smaller than the median (Data[mid]), then it Print("This is what you're looking for. [%s]! "%Data[mid])Else: Print("Sorry, did not find the value you want ...")if __name__=='__main__': #create a continuous array of numbers from 1 to 60 milliondata = List (range (60000000)) #call function to find 95938 valueSearch_data (data,95938)
examples of related codeList Lookup
List lookup: Find the specified element from the list
Input: list, find element
Output: element subscript or no element found
There are generally two ways to do this:
1. Sequential Search
Start with the first element of the list and search in order until you find it.
def linear_search (Data_set,value): For i in Data_set: if data_set[i] = = value: return I
2, two-point search
Starting from the candidate area of the ordered list Data[0:n], the candidate area can be halved by comparing the value of the lookup with the median of the candidate area.
def bin_search (data_set,value): Low = 0 High = Len (data_set)-1 when Low <= High: mid = (Low+high)//2 if data_set[mid] = = value: return mid elif Data_set[mid] > value: High = mid-1 else: low = m ID + 1
defBin_search (data_set,value,low,high):ifLow <=High:mid= (Low+high)//2ifData_set[mid] = =Value:returnMidelifData_set[mid] >Value:returnBin_search (Data_set,value,low,high)Else: returnBin_search (Data_set, value, low, high)Else: return
find recursive version of binary
Exercises:
a list of learners ' information is available in the form of an ORDER by ID: [{"id": 1001, "name": "Zhang San", "Age": 20},{"id": 1002, " Name ': ' John Doe ', ' age ': 25},{' id ': 1004, ' name ': ' Harry ', ' Age ': 23},{' id ': 1007, ' name ': ' Zhao Liu ', ' Age ': 33}] Modify the binary lookup code, enter the student ID, Output the student's subscript in the list and output the complete student information.
L = [{"id": 1001, "name": "Zhang San", "Age": $}, {"id": 1002, "name": "John Doe", "Age": +}, {"id": 1004, "name": "Harry", "Age": 23}, {"id": 1007, "name": "Zhao Liu", "Age": 33}] def bin_search (Data_set,value): "" "Binary lookup:p Aram Data_set: List:p Aram value: value to check: return:" "low = 0 High = Len (data_set)-1 when low <= High:mid = (low+high)//2 if data_set[mid][' id '] = = value: Return (Mid,data_set[mid]) elif data_set[mid][' id '] > value:high = mid-1 Else: Low = mid + 1 Else:return (0,none) flog = truewhile Flog:sid = input ("Enter the study number (exit: Q):"). Strip () if SID . IsDigit (): if sid.upper () = = "Q": Flog = False else:sid = int (SID) Mid,in FOS = Bin_search (l,sid) if not infos:print ("Check no this person!!!" ") else:s =" Student number: {ID}, Name: {name}, Age: {ages} ". Format (**infos) print (" The student's information index coordinates:%s "%mid" Print ("All information for the student:%s "%s"
Algorithm foreplay recursive binary lookup list lookup