0

Python help, can you give me a quick one line help to the code?

https://code.sololearn.com/cUB8g88UMbkR/?ref=app Hi guys, I have attached a copy from a snippet of my code and college. Can you help give me a very short explanation to what each line of code is doing on it please? Thank you!

22nd Nov 2019, 1:47 PM
Rob
5 Respuestas
+ 1
4/4 # Iterative Binary Search function # log (N) of a billion is 30 iterations. def binary_search_iterative(data, target): #low = lowest value or first element in the sorted array . low = 0 #high = greatest value the last elementin the sorted array. #because indices start from 0 we have to do - 1 not get out of range. high = len(data) - 1 # iterate as long as low is less than or equal high while low <= high: #get the value at the middle of the array . by dividing its length by 2 mid = (low + high) // 2 # check if target is found in the middle if target == data[mid]: return True #else check which half has the target value #lower half elif target < data[mid]: high = mid - 1 #higher half else: low = mid + 1 return False
22nd Nov 2019, 4:34 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
1/4 the code contains two functions one is for linear search, the other is binary search. linear search works by looking for the value starting from element zero until it finds the value and stops or continues until the end, finding it or does not find it at all
22nd Nov 2019, 4:32 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
2/4 # Linear Search function #data = the array to search #target = the searched value def linear_search(data, target): # for loop to iterate through the data until it finds a target for i in range(len(data)): # check if there is a match #the range is the length of data #( i)will be incremented until it find a match or reach the end of data if data[i] == target: #return true if a match is found return True # false if no match is found return False
22nd Nov 2019, 4:33 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
3/4 binary search is performed on a sorted array which means data in data has to be sorted. the least value in element 0 and the greatest at the last element ,(length of data - 1). the way binary search works is it takes the numberof elements in data an divide it by 2 to get to the middle and compare it. if target is less than midvalue we know the value is in the first half otherwise it is in the second half. we repeat the same operation on the correct half and divide it by 2 and check again until the value is found or not found. best case scenario we land on the value in the first try.
22nd Nov 2019, 4:34 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
thank you so much buhha! this had made so much sence from reading your discription
22nd Nov 2019, 6:20 PM
Rob