Need explain about the code - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Need explain about the code (/thread-21072.html) |
Need explain about the code - ap111 - Sep-12-2019 i worte this code: import time def search_lst(L, x): mone = 0 for i in range(len(L)-1): if x == L[i]: return True return False def binary_search(L, x): left = 0 right = len(L) - 1 while left <= right: mid = (left + right) // 2 if x == L[mid]: return True else: if x < L[mid]: # go to left half right = mid - 1 else: # go to right half left = mid + 1 return False # if we got here the search failed lst = [3, 4, 5, 6, 9, 10, 13, 16, 18, 20, 22, 28, 29, 31, 32, 33, 40, 42, 47, 48, 50, 52] start = time.perf_counter() result = binary_search(lst, 52) print(result) end = time.perf_counter() print(end-start) s = time.perf_counter() result = search_lst(lst,3) print(result) e = time.perf_counter() print(s-e) I wanted to compare the times of the functions. But the second comparison (with the variables 'e' and 's') was negative and I wanted to know why? Thanks. RE: Need explain about the code - ichabod801 - Sep-12-2019 It's returns the seconds elapsed since a certain point in time. So the end values are larger than the start values. You want to reverse your second subtraction, so it matches the first one. RE: Need explain about the code - luoheng - Sep-12-2019 It's e-s , not s-e in line 34.
|